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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import shutil
|
| 4 |
+
import asyncio
|
| 5 |
+
import io
|
| 6 |
+
import re
|
| 7 |
+
import jdatetime
|
| 8 |
+
import ffmpeg
|
| 9 |
+
from fastapi import FastAPI, BackgroundTasks, HTTPException, Security, Depends
|
| 10 |
+
from fastapi.security.api_key import APIKeyHeader
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
import gradio as gr
|
| 13 |
+
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 |
+
|
| 41 |
+
class Segment(BaseModel):
|
| 42 |
+
start_time: str
|
| 43 |
+
end_time: str
|
| 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:
|
| 54 |
+
try:
|
| 55 |
+
year, month, day = map(int, match.groups())
|
| 56 |
+
shamsi_date = jdatetime.date(year, month, day)
|
| 57 |
+
except ValueError:
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
text_without_date = re.sub(r"(\d{4})/(\d{1,2})/(\d{1,2})", "", text).strip()
|
| 61 |
+
lines = [line.strip() for line in text_without_date.split('\n') if line.strip()]
|
| 62 |
+
|
| 63 |
+
previous_end_time = '00:00:00'
|
| 64 |
+
for i in range(0, len(lines), 3):
|
| 65 |
+
chunk = lines[i:i+3]
|
| 66 |
+
if len(chunk) == 3:
|
| 67 |
+
segment = Segment(start_time=previous_end_time, end_time=chunk[0], title=chunk[1], artist=chunk[2])
|
| 68 |
+
segments.append(segment)
|
| 69 |
+
previous_end_time = chunk[0]
|
| 70 |
+
return segments, shamsi_date
|
| 71 |
+
|
| 72 |
+
# --- پردازشگر اصلی (Background Task) ---
|
| 73 |
+
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()
|
| 81 |
+
try:
|
| 82 |
+
segments, shamsi_date = parse_user_commands(data.commands_text)
|
| 83 |
+
if not segments:
|
| 84 |
+
await pyro_client.send_message(chat_id=data.chat_id, text="فرمت دستورات اشتباه است.")
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
# 1. دانلود فایل اصلی از طریق پیام ارسال شده
|
| 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 |
+
# 2. پردازش کاور (در صورت وجود)
|
| 92 |
+
cover_data = None
|
| 93 |
+
if data.cover_message_id:
|
| 94 |
+
cover_path = os.path.join(temp_dir, "cover.jpg")
|
| 95 |
+
await pyro_client.download_media(message=data.cover_message_id, file_name=cover_path)
|
| 96 |
+
try:
|
| 97 |
+
with Image.open(cover_path) as img:
|
| 98 |
+
img = img.convert('RGB')
|
| 99 |
+
img.thumbnail((800, 800))
|
| 100 |
+
output_io = io.BytesIO()
|
| 101 |
+
img.save(output_io, format='JPEG', quality=85, optimize=True)
|
| 102 |
+
cover_data = output_io.getvalue()
|
| 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 |
+
ffmpeg.input(original_media_path, ss=seg.start_time, to=seg.end_time).output(
|
| 114 |
+
output_filepath, acodec='libmp3lame', ab='128k', map_metadata='-1', **{'id3v2_version': '3'}
|
| 115 |
+
).run(overwrite_output=True, quiet=True)
|
| 116 |
+
|
| 117 |
+
# 4. افزودن تگها با Mutagen
|
| 118 |
+
audio = MP3(output_filepath, ID3=ID3)
|
| 119 |
+
actual_duration = int(audio.info.length)
|
| 120 |
+
audio.delete()
|
| 121 |
+
audio.tags = ID3()
|
| 122 |
+
audio.tags.add(TIT2(encoding=3, text=seg.title))
|
| 123 |
+
audio.tags.add(TPE2(encoding=3, text=seg.artist))
|
| 124 |
+
if cover_data:
|
| 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 |
+
# 5. ارسال خروجی (پشتیبانی پایروگرام تا حجم بالا)
|
| 129 |
+
thumb_path = None
|
| 130 |
+
if cover_data:
|
| 131 |
+
thumb_path = os.path.join(temp_dir, "thumb.jpg")
|
| 132 |
+
with open(thumb_path, 'wb') as t:
|
| 133 |
+
t.write(cover_data)
|
| 134 |
+
|
| 135 |
+
await pyro_client.send_audio(
|
| 136 |
+
chat_id=data.chat_id,
|
| 137 |
+
audio=output_filepath,
|
| 138 |
+
title=seg.title,
|
| 139 |
+
performer=seg.artist,
|
| 140 |
+
file_name=final_filename,
|
| 141 |
+
duration=actual_duration,
|
| 142 |
+
thumb=thumb_path
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
except Exception as e:
|
| 146 |
+
await pyro_client.send_message(chat_id=data.chat_id, text=f"خطا در پردازش: {str(e)}")
|
| 147 |
+
finally:
|
| 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": "Heavy processing started securely"}
|
| 157 |
+
|
| 158 |
+
# --- رابط کاربری فرمالیته برای دور زدن محدودیت هاگینگفیس ---
|
| 159 |
+
def dummy_ui():
|
| 160 |
+
return "سیستم پردازش ابری فعال است و در پسزمینه به درخواستهای API گوش میدهد."
|
| 161 |
+
|
| 162 |
+
demo = gr.Interface(fn=dummy_ui, inputs=None, outputs="text", title="Audio Processing Engine")
|
| 163 |
+
|
| 164 |
+
# ادغام Gradio و FastAPI
|
| 165 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|