|
| 1 | +import asyncio |
| 2 | +import random |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import anyio |
| 6 | + |
| 7 | +from app.core.celery import celery_app |
| 8 | +from app.services.callback import callback_audio_with_info, callback_failed |
| 9 | + |
| 10 | +SONG_PATH = "resource/sing/splices/" |
| 11 | +MUSIC_PATH = "resource/music/" |
| 12 | + |
| 13 | + |
| 14 | +def get_random_song(speaker: str = ""): |
| 15 | + all_song = [] |
| 16 | + song_dir = Path(SONG_PATH) |
| 17 | + if song_dir.exists(): |
| 18 | + all_song = [str(s) for s in song_dir.iterdir() if speaker in s.name and "_spliced0" not in s.name] |
| 19 | + |
| 20 | + if not all_song: |
| 21 | + music_dir = Path(MUSIC_PATH) |
| 22 | + if music_dir.exists(): |
| 23 | + all_song = [str(s) for s in music_dir.iterdir()] |
| 24 | + |
| 25 | + if not all_song: |
| 26 | + return None |
| 27 | + return random.choice(all_song) |
| 28 | + |
| 29 | + |
| 30 | +@celery_app.task(name="play") |
| 31 | +def play_task(request_id: str, speaker: str = ""): |
| 32 | + loop = asyncio.new_event_loop() |
| 33 | + asyncio.set_event_loop(loop) |
| 34 | + try: |
| 35 | + return loop.run_until_complete(_play_task_async(request_id, speaker)) |
| 36 | + finally: |
| 37 | + loop.close() |
| 38 | + |
| 39 | + |
| 40 | +async def _play_task_async(request_id: str, speaker: str = ""): |
| 41 | + try: |
| 42 | + rand_music = get_random_song(speaker) |
| 43 | + if not rand_music: |
| 44 | + await callback_failed(request_id) |
| 45 | + return False |
| 46 | + |
| 47 | + if "_spliced" in rand_music: |
| 48 | + splited = Path(rand_music).stem.split("_") |
| 49 | + song_id = splited[0] |
| 50 | + chunk_index = int(splited[1].replace("spliced", "")) + 1 |
| 51 | + if "key" in rand_music: |
| 52 | + key_index = next((i for i, part in enumerate(splited) if "key" in part), None) |
| 53 | + if key_index is not None: |
| 54 | + try: |
| 55 | + key = int(splited[key_index].replace("key", "")) |
| 56 | + except ValueError: |
| 57 | + key = 0 |
| 58 | + else: |
| 59 | + key = 0 |
| 60 | + else: |
| 61 | + key = 0 |
| 62 | + elif "_full_" in rand_music: |
| 63 | + song_id = Path(rand_music).stem.split("_")[0] |
| 64 | + chunk_index = 114514 |
| 65 | + key = 0 |
| 66 | + else: |
| 67 | + song_id = "" |
| 68 | + chunk_index = 114514 |
| 69 | + key = 0 |
| 70 | + |
| 71 | + try: |
| 72 | + async with await anyio.open_file(rand_music, "rb") as f: |
| 73 | + audio_content = await f.read() |
| 74 | + except Exception: |
| 75 | + await callback_failed(request_id) |
| 76 | + return False |
| 77 | + |
| 78 | + await callback_audio_with_info(request_id, audio_content, song_id=song_id, chunk_index=chunk_index, key=key) |
| 79 | + return True |
| 80 | + except Exception: |
| 81 | + await callback_failed(request_id) |
| 82 | + return False |
0 commit comments