File size: 2,369 Bytes
4305459
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# app.py

import os
import shutil
import tempfile
import torch
import whisper
from fastapi import FastAPI, File, UploadFile, Query
from typing import Dict, Optional

# --- الإعدادات الأولية وتحميل النموذج ---

# تحديد الجهاز (GPU إذا كان متاحًا، وإلا CPU)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {DEVICE}")

# تحميل النموذج (سنستخدم 'base' للبساطة والسرعة في الخطة المجانية)
print("Loading 'base' model...")
model = whisper.load_model("base", device=DEVICE)
print("Model 'base' loaded successfully.")

# إنشاء تطبيق FastAPI
app = FastAPI()

# --- نقاط النهاية (Endpoints) ---

@app.get("/")
def read_root():
    """ نقطة نهاية للتحقق من أن الـ API يعمل. """
    return {"message": "Whisper API is running. Use the /transcribe endpoint to submit audio files."}

@app.post("/transcribe")
async def transcribe_audio(
    file: UploadFile = File(...),
    language: Optional[str] = Query(None, description="Language of the audio (e.g., 'ar' for Arabic)")
):
    """
    نقطة نهاية لتحويل ملف صوتي إلى نص.
    تقبل ملفًا صوتيًا وتُرجع النص المحوّل.
    """
    # Whisper يحتاج إلى قراءة الملف من مسار على القرص، لذلك نحفظه مؤقتًا
    with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp_file:
        shutil.copyfileobj(file.file, tmp_file)
        tmp_file_path = tmp_file.name

    try:
        # تحديد خيارات التحويل (مثل اللغة إذا تم تحديدها)
        transcribe_options = {"language": language} if language else {}
        
        # استدعاء النموذج للقيام بالتحويل
        result = model.transcribe(tmp_file_path, **transcribe_options)
        
        transcript = result.get("text", "لم يتمكن من التعرف على نص.")
        detected_language = result.get("language", "لم يتم تحديد اللغة.")
        
        return {"transcript": transcript, "language": detected_language}

    finally:
        # التأكد من حذف الملف المؤقت بعد الانتهاء
        os.remove(tmp_file_path)
        await file.close()