Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import uuid
|
| 3 |
import shutil
|
| 4 |
-
import asyncio
|
| 5 |
import io
|
| 6 |
import re
|
| 7 |
import jdatetime
|
|
@@ -14,27 +13,28 @@ from pyrogram import Client
|
|
| 14 |
from mutagen.mp3 import MP3
|
| 15 |
from mutagen.id3 import ID3, TIT2, TPE2, TDRC, APIC
|
| 16 |
from PIL import Image
|
|
|
|
| 17 |
|
| 18 |
# --- تنظیمات و متغیرهای محیطی ---
|
| 19 |
API_ID = int(os.environ.get("API_ID", "1234567"))
|
| 20 |
API_HASH = os.environ.get("API_HASH", "")
|
| 21 |
BOT_TOKEN = os.environ.get("TELEGRAM_TOKEN", "")
|
| 22 |
-
API_SECRET_KEY = os.environ.get("API_SECRET_KEY", "my_super_secret_key_123")
|
| 23 |
|
| 24 |
app = FastAPI()
|
| 25 |
|
| 26 |
-
# --- لایه امنیتی ---
|
| 27 |
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
|
| 28 |
|
| 29 |
def verify_api_key(api_key: str = Security(api_key_header)):
|
| 30 |
if api_key != API_SECRET_KEY:
|
| 31 |
-
raise HTTPException(status_code=403, detail="دسترسی غیرمجاز. کلید
|
| 32 |
return api_key
|
| 33 |
|
| 34 |
-
# --- مدل
|
| 35 |
class JobRequest(BaseModel):
|
| 36 |
chat_id: int
|
| 37 |
-
media_message_id: int
|
| 38 |
commands_text: str
|
| 39 |
cover_message_id: int | None = None
|
| 40 |
|
|
@@ -44,10 +44,20 @@ class Segment(BaseModel):
|
|
| 44 |
title: str
|
| 45 |
artist: str
|
| 46 |
|
| 47 |
-
# --- ت
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
def parse_user_commands(text: str):
|
| 49 |
segments = []
|
| 50 |
-
shamsi_date = jdatetime.date.today()
|
| 51 |
|
| 52 |
match = re.search(r"(\d{4})/(\d{1,2})/(\d{1,2})", text)
|
| 53 |
if match:
|
|
@@ -74,7 +84,6 @@ async def process_heavy_file(data: JobRequest):
|
|
| 74 |
temp_dir = f"temp_{data.chat_id}_{uuid.uuid4()}"
|
| 75 |
os.makedirs(temp_dir, exist_ok=True)
|
| 76 |
|
| 77 |
-
# کلاینت پایروگرام فقط برای همین یک درخواست روشن و سپس خاموش میشود
|
| 78 |
pyro_client = Client("bot_session", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)
|
| 79 |
|
| 80 |
await pyro_client.start()
|
|
@@ -84,11 +93,11 @@ async def process_heavy_file(data: JobRequest):
|
|
| 84 |
await pyro_client.send_message(chat_id=data.chat_id, text="فرمت دستورات اشتباه است.")
|
| 85 |
return
|
| 86 |
|
| 87 |
-
#
|
| 88 |
original_media_path = os.path.join(temp_dir, "input_media")
|
| 89 |
await pyro_client.download_media(message=data.media_message_id, file_name=original_media_path)
|
| 90 |
|
| 91 |
-
#
|
| 92 |
cover_data = None
|
| 93 |
if data.cover_message_id:
|
| 94 |
cover_path = os.path.join(temp_dir, "cover.jpg")
|
|
@@ -103,18 +112,16 @@ async def process_heavy_file(data: JobRequest):
|
|
| 103 |
except Exception:
|
| 104 |
pass
|
| 105 |
|
| 106 |
-
# 3. پردازش و برش با FFMPEG
|
| 107 |
date_filename_part = shamsi_date.strftime("%Y%m%d")
|
| 108 |
for seg in segments:
|
| 109 |
safe_title = re.sub(r'[\\/*?:"<>|]', "", seg.title)
|
| 110 |
final_filename = f"{date_filename_part}-{safe_title}.mp3"
|
| 111 |
output_filepath = os.path.join(temp_dir, final_filename)
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
).run(overwrite_output=True, quiet=True)
|
| 116 |
|
| 117 |
-
#
|
| 118 |
audio = MP3(output_filepath, ID3=ID3)
|
| 119 |
actual_duration = int(audio.info.length)
|
| 120 |
audio.delete()
|
|
@@ -125,7 +132,7 @@ async def process_heavy_file(data: JobRequest):
|
|
| 125 |
audio.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=cover_data))
|
| 126 |
audio.save(v2_version=3)
|
| 127 |
|
| 128 |
-
#
|
| 129 |
thumb_path = None
|
| 130 |
if cover_data:
|
| 131 |
thumb_path = os.path.join(temp_dir, "thumb.jpg")
|
|
@@ -148,18 +155,16 @@ async def process_heavy_file(data: JobRequest):
|
|
| 148 |
await pyro_client.stop()
|
| 149 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 150 |
|
| 151 |
-
# --- اندپوینت دریافت سیگنال ---
|
| 152 |
@app.post("/trigger")
|
| 153 |
async def trigger_process(job: JobRequest, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
|
| 154 |
-
# دریافت تاییدیه فقط در صورتی انجام میشود که API_KEY درست باشد
|
| 155 |
background_tasks.add_task(process_heavy_file, job)
|
| 156 |
-
return {"status": "ok", "message": "
|
| 157 |
|
| 158 |
-
# --- رابط کاربری فرمالیته
|
| 159 |
def dummy_ui():
|
| 160 |
-
return "
|
| 161 |
|
| 162 |
-
demo = gr.Interface(fn=dummy_ui, inputs=None, outputs="text", title="Audio Processing
|
| 163 |
|
| 164 |
-
# ادغام Gradio و FastAPI
|
| 165 |
app = gr.mount_gradio_app(app, demo, path="/")
|
|
|
|
| 1 |
import os
|
| 2 |
import uuid
|
| 3 |
import shutil
|
|
|
|
| 4 |
import io
|
| 5 |
import re
|
| 6 |
import jdatetime
|
|
|
|
| 13 |
from mutagen.mp3 import MP3
|
| 14 |
from mutagen.id3 import ID3, TIT2, TPE2, TDRC, APIC
|
| 15 |
from PIL import Image
|
| 16 |
+
import spaces # اضافه شدن کتابخانه اختصاصی هاگینگفیس
|
| 17 |
|
| 18 |
# --- تنظیمات و متغیرهای محیطی ---
|
| 19 |
API_ID = int(os.environ.get("API_ID", "1234567"))
|
| 20 |
API_HASH = os.environ.get("API_HASH", "")
|
| 21 |
BOT_TOKEN = os.environ.get("TELEGRAM_TOKEN", "")
|
| 22 |
+
API_SECRET_KEY = os.environ.get("API_SECRET_KEY", "my_super_secret_key_123")
|
| 23 |
|
| 24 |
app = FastAPI()
|
| 25 |
|
| 26 |
+
# --- لایه امنیتی برای ارتباط با کلودفلر ---
|
| 27 |
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
|
| 28 |
|
| 29 |
def verify_api_key(api_key: str = Security(api_key_header)):
|
| 30 |
if api_key != API_SECRET_KEY:
|
| 31 |
+
raise HTTPException(status_code=403, detail="دسترسی غیرمجاز. کلید نامعتبر است.")
|
| 32 |
return api_key
|
| 33 |
|
| 34 |
+
# --- مدلهای Pydantic ---
|
| 35 |
class JobRequest(BaseModel):
|
| 36 |
chat_id: int
|
| 37 |
+
media_message_id: int
|
| 38 |
commands_text: str
|
| 39 |
cover_message_id: int | None = None
|
| 40 |
|
|
|
|
| 44 |
title: str
|
| 45 |
artist: str
|
| 46 |
|
| 47 |
+
# --- تابع ایزوله شده برای استفاده از GPU (دور زدن محدودیت هاگینگفیس) ---
|
| 48 |
+
@spaces.GPU(duration=120)
|
| 49 |
+
def extract_and_convert_audio_on_gpu(input_path, start_time, end_time, output_path):
|
| 50 |
+
try:
|
| 51 |
+
ffmpeg.input(input_path, ss=start_time, to=end_time).output(
|
| 52 |
+
output_path, acodec='libmp3lame', ab='128k', map_metadata='-1', **{'id3v2_version': '3'}
|
| 53 |
+
).run(overwrite_output=True, quiet=True, capture_stderr=True)
|
| 54 |
+
except ffmpeg.Error as e:
|
| 55 |
+
raise Exception(f"FFmpeg Error: {e.stderr.decode('utf-8', errors='replace')}")
|
| 56 |
+
|
| 57 |
+
# --- توابع کمکی پارس کردن متن ---
|
| 58 |
def parse_user_commands(text: str):
|
| 59 |
segments = []
|
| 60 |
+
shamsi_date = jdatetime.date.today()
|
| 61 |
|
| 62 |
match = re.search(r"(\d{4})/(\d{1,2})/(\d{1,2})", text)
|
| 63 |
if match:
|
|
|
|
| 84 |
temp_dir = f"temp_{data.chat_id}_{uuid.uuid4()}"
|
| 85 |
os.makedirs(temp_dir, exist_ok=True)
|
| 86 |
|
|
|
|
| 87 |
pyro_client = Client("bot_session", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)
|
| 88 |
|
| 89 |
await pyro_client.start()
|
|
|
|
| 93 |
await pyro_client.send_message(chat_id=data.chat_id, text="فرمت دستورات اشتباه است.")
|
| 94 |
return
|
| 95 |
|
| 96 |
+
# دانلود مدیا
|
| 97 |
original_media_path = os.path.join(temp_dir, "input_media")
|
| 98 |
await pyro_client.download_media(message=data.media_message_id, file_name=original_media_path)
|
| 99 |
|
| 100 |
+
# پردازش کاور
|
| 101 |
cover_data = None
|
| 102 |
if data.cover_message_id:
|
| 103 |
cover_path = os.path.join(temp_dir, "cover.jpg")
|
|
|
|
| 112 |
except Exception:
|
| 113 |
pass
|
| 114 |
|
|
|
|
| 115 |
date_filename_part = shamsi_date.strftime("%Y%m%d")
|
| 116 |
for seg in segments:
|
| 117 |
safe_title = re.sub(r'[\\/*?:"<>|]', "", seg.title)
|
| 118 |
final_filename = f"{date_filename_part}-{safe_title}.mp3"
|
| 119 |
output_filepath = os.path.join(temp_dir, final_filename)
|
| 120 |
|
| 121 |
+
# فراخوانی تابع گرافیکی برای برش مدیا
|
| 122 |
+
extract_and_convert_audio_on_gpu(original_media_path, seg.start_time, seg.end_time, output_filepath)
|
|
|
|
| 123 |
|
| 124 |
+
# افزودن تگها با Mutagen
|
| 125 |
audio = MP3(output_filepath, ID3=ID3)
|
| 126 |
actual_duration = int(audio.info.length)
|
| 127 |
audio.delete()
|
|
|
|
| 132 |
audio.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=cover_data))
|
| 133 |
audio.save(v2_version=3)
|
| 134 |
|
| 135 |
+
# ارسال خروجی با Pyrogram
|
| 136 |
thumb_path = None
|
| 137 |
if cover_data:
|
| 138 |
thumb_path = os.path.join(temp_dir, "thumb.jpg")
|
|
|
|
| 155 |
await pyro_client.stop()
|
| 156 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 157 |
|
| 158 |
+
# --- اندپوینت دریافت سیگنال از سرورلس کلودفلر ---
|
| 159 |
@app.post("/trigger")
|
| 160 |
async def trigger_process(job: JobRequest, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
|
|
|
|
| 161 |
background_tasks.add_task(process_heavy_file, job)
|
| 162 |
+
return {"status": "ok", "message": "Processing started on ZeroGPU"}
|
| 163 |
|
| 164 |
+
# --- رابط کاربری فرمالیته Gradio ---
|
| 165 |
def dummy_ui():
|
| 166 |
+
return "API Engine is running on Hugging Face ZeroGPU!"
|
| 167 |
|
| 168 |
+
demo = gr.Interface(fn=dummy_ui, inputs=None, outputs="text", title="Cloud Audio Processing")
|
| 169 |
|
|
|
|
| 170 |
app = gr.mount_gradio_app(app, demo, path="/")
|