FileProcess / app.py
amir133k's picture
Update app.py
21557ea verified
Raw History Blame Contribute Delete
6.88 kB
import os
import uuid
import shutil
import io
import re
import jdatetime
import ffmpeg
from fastapi import FastAPI, BackgroundTasks, HTTPException, Security, Depends
from fastapi.security.api_key import APIKeyHeader
from pydantic import BaseModel
import gradio as gr
from pyrogram import Client
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, TIT2, TPE2, TDRC, APIC
from PIL import Image
import spaces # اضافه شدن کتابخانه اختصاصی هاگینگ‌فیس
# --- تنظیمات و متغیرهای محیطی ---
API_ID = int(os.environ.get("API_ID", "1234567"))
API_HASH = os.environ.get("API_HASH", "")
BOT_TOKEN = os.environ.get("TELEGRAM_TOKEN", "")
API_SECRET_KEY = os.environ.get("API_SECRET_KEY", "my_super_secret_key_123")
app = FastAPI()
# --- لایه امنیتی برای ارتباط با کلودفلر ---
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
def verify_api_key(api_key: str = Security(api_key_header)):
if api_key != API_SECRET_KEY:
raise HTTPException(status_code=403, detail="دسترسی غیرمجاز. کلید نامعتبر است.")
return api_key
# --- مدل‌های Pydantic ---
class JobRequest(BaseModel):
chat_id: int
media_message_id: int
commands_text: str
cover_message_id: int | None = None
class Segment(BaseModel):
start_time: str
end_time: str
title: str
artist: str
# --- تابع ایزوله شده برای استفاده از GPU (دور زدن محدودیت هاگینگ‌فیس) ---
@spaces.GPU(duration=120)
def extract_and_convert_audio_on_gpu(input_path, start_time, end_time, output_path):
try:
ffmpeg.input(input_path, ss=start_time, to=end_time).output(
output_path, acodec='libmp3lame', ab='128k', map_metadata='-1', **{'id3v2_version': '3'}
).run(overwrite_output=True, quiet=True, capture_stderr=True)
except ffmpeg.Error as e:
raise Exception(f"FFmpeg Error: {e.stderr.decode('utf-8', errors='replace')}")
# --- توابع کمکی پارس کردن متن ---
def parse_user_commands(text: str):
segments = []
shamsi_date = jdatetime.date.today()
match = re.search(r"(\d{4})/(\d{1,2})/(\d{1,2})", text)
if match:
try:
year, month, day = map(int, match.groups())
shamsi_date = jdatetime.date(year, month, day)
except ValueError:
pass
text_without_date = re.sub(r"(\d{4})/(\d{1,2})/(\d{1,2})", "", text).strip()
lines = [line.strip() for line in text_without_date.split('\n') if line.strip()]
previous_end_time = '00:00:00'
for i in range(0, len(lines), 3):
chunk = lines[i:i+3]
if len(chunk) == 3:
segment = Segment(start_time=previous_end_time, end_time=chunk[0], title=chunk[1], artist=chunk[2])
segments.append(segment)
previous_end_time = chunk[0]
return segments, shamsi_date
# --- پردازشگر اصلی (Background Task) ---
async def process_heavy_file(data: JobRequest):
temp_dir = f"temp_{data.chat_id}_{uuid.uuid4()}"
os.makedirs(temp_dir, exist_ok=True)
pyro_client = Client("bot_session", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)
await pyro_client.start()
try:
segments, shamsi_date = parse_user_commands(data.commands_text)
if not segments:
await pyro_client.send_message(chat_id=data.chat_id, text="فرمت دستورات اشتباه است.")
return
# دانلود مدیا
original_media_path = os.path.join(temp_dir, "input_media")
await pyro_client.download_media(message=data.media_message_id, file_name=original_media_path)
# پردازش کاور
cover_data = None
if data.cover_message_id:
cover_path = os.path.join(temp_dir, "cover.jpg")
await pyro_client.download_media(message=data.cover_message_id, file_name=cover_path)
try:
with Image.open(cover_path) as img:
img = img.convert('RGB')
img.thumbnail((800, 800))
output_io = io.BytesIO()
img.save(output_io, format='JPEG', quality=85, optimize=True)
cover_data = output_io.getvalue()
except Exception:
pass
date_filename_part = shamsi_date.strftime("%Y%m%d")
for seg in segments:
safe_title = re.sub(r'[\\/*?:"<>|]', "", seg.title)
final_filename = f"{date_filename_part}-{safe_title}.mp3"
output_filepath = os.path.join(temp_dir, final_filename)
# فراخوانی تابع گرافیکی برای برش مدیا
extract_and_convert_audio_on_gpu(original_media_path, seg.start_time, seg.end_time, output_filepath)
# افزودن تگ‌ها با Mutagen
audio = MP3(output_filepath, ID3=ID3)
actual_duration = int(audio.info.length)
audio.delete()
audio.tags = ID3()
audio.tags.add(TIT2(encoding=3, text=seg.title))
audio.tags.add(TPE2(encoding=3, text=seg.artist))
if cover_data:
audio.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=cover_data))
audio.save(v2_version=3)
# ارسال خروجی با Pyrogram
thumb_path = None
if cover_data:
thumb_path = os.path.join(temp_dir, "thumb.jpg")
with open(thumb_path, 'wb') as t:
t.write(cover_data)
await pyro_client.send_audio(
chat_id=data.chat_id,
audio=output_filepath,
title=seg.title,
performer=seg.artist,
file_name=final_filename,
duration=actual_duration,
thumb=thumb_path
)
except Exception as e:
await pyro_client.send_message(chat_id=data.chat_id, text=f"خطا در پردازش: {str(e)}")
finally:
await pyro_client.stop()
shutil.rmtree(temp_dir, ignore_errors=True)
# --- اندپوینت دریافت سیگنال از سرورلس کلودفلر ---
@app.post("/trigger")
async def trigger_process(job: JobRequest, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
background_tasks.add_task(process_heavy_file, job)
return {"status": "ok", "message": "Processing started on ZeroGPU"}
# --- رابط کاربری فرمالیته Gradio ---
def dummy_ui():
return "API Engine is running on Hugging Face ZeroGPU!"
demo = gr.Interface(fn=dummy_ui, inputs=None, outputs="text", title="Cloud Audio Processing")
app = gr.mount_gradio_app(app, demo, path="/")