File size: 4,343 Bytes
1631029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import os
import requests
import time

from pdfminer.high_level import extract_text
from docx import Document
# تحميل متغيرات البيئة
HUGGING_FACE_API_KEY = os.environ.get("HUGGING_FACE_API_KEY")

print("HUGGING_FACE_API_KEY:", HUGGING_FACE_API_KEY)


# دالة تلخيص النصوص
def summarizer(text):
    url = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
    headers = {"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"}
    payload = {"inputs": text}

    response = requests.post(url, headers=headers, json=payload)
    
    # ✅ طباعة حالة الاستجابة لمعرفة هل هناك خطأ؟
    print("API Response Status Code:", response.status_code)
    
    try:
        response_json = response.json()  # تحويل الاستجابة إلى JSON
        print("API Response:", response_json)
    except Exception as e:
        print("Error parsing response JSON:", e)

    return response.json()


# دالة توليد وصف الصور
def image_captioning(image_bytes):
    url = "https://api-inference.huggingface.co/models/nlpconnect/vit-gpt2-image-captioning"
    headers = {"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"}
    
    response = requests.post(url, headers=headers, files={"file": ("image.jpg", image_bytes, "image/jpeg")})
    return response.json()

# دالة الإجابة على الأسئلة
def qa_pipeline(question, context):
    url = "https://api-inference.huggingface.co/models/deepset/roberta-base-squad2"
    headers = {"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"}
    payload = {"inputs": {"question": question, "context": context}}

    response = requests.post(url, headers=headers, json=payload)
    return response.json()

# دالة الترجمة بين اللغات المدعومة
def translator(text, source_lang, target_lang):
    # تحقق من أن اللغات مدعومة
    supported_langs = ['en', 'fr', 'es', 'ar', 'zh']
    if source_lang not in supported_langs or target_lang not in supported_langs:
        return {"error": "there is not support , supported languages: en, fr, es, ar, zh"}

    # توليد اسم النموذج بناءً على اللغات
    model_name = f"Helsinki-NLP/opus-mt-{source_lang}-{target_lang}"
    url = f"https://api-inference.huggingface.co/models/{model_name}"
    headers = {"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"}
    payload = {"inputs": text}

    # إرسال الطلب
    response = requests.post(url, headers=headers, json=payload)

    # معالجة الأخطاء المحتملة
    try:
        return response.json()
    except Exception as e:
        return {"error": str(e)}


# دالة توليد كود التصور البياني
def code_generator(prompt: str, max_retries: int = 3) -> dict:

    url = "https://api-inference.huggingface.co/models/Salesforce/codegen-350M-multi"
    headers = {"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"}
    
    for attempt in range(max_retries):
        try:
            response = requests.post(
                url,
                headers=headers,
                json={"inputs": prompt},
                timeout=30  # زيادة الوقت لانتظار النموذج
            )
            
            # تحقق من حالة الاستجابة
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 503:
                print(f"API is overloaded. Retrying in 5 seconds... Attempt {attempt + 1}/{max_retries}...")
                time.sleep(5)  # انتظر قبل إعادة المحاولة
            else:
                return {"error": f"API Error: {response.status_code}", "details": response.text}
                
        except requests.exceptions.RequestException as e:
            return {"error": f"Connection Error: {str(e)}"}
    
    return {"error": "Failed to generate code after multiple attempts."}


def extract_text_from_document(path):
    if path.endswith(".pdf"):
        return extract_text(path)
    elif path.endswith(".docx"):
        doc = Document(path)
        return "\n".join([p.text for p in doc.paragraphs])
    elif path.endswith(".txt"):
        with open(path, encoding="utf-8") as f:
            return f.read()
    else:
        return "Unsupported file format."