NaserNajeh commited on
Commit
7d26757
·
verified ·
1 Parent(s): 1532fcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -60
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import os, io, base64, traceback
2
  import gradio as gr
3
  import fitz # PyMuPDF
4
  from PIL import Image
@@ -25,12 +25,12 @@ def ocr_easyocr(pil_img: Image.Image) -> str:
25
 
26
  # ===============================================
27
  # 2) Inference API (يستهلك اعتمادات PRO بدل دقائق GPU)
28
- # نحاول VQA أولاً ثم نسقط إلى image_to_text ثم chat.completions
29
  # ===============================================
30
  from huggingface_hub import InferenceClient
31
  _INFER_CLIENT = None
32
- # يمكن تغيير الموديل من Settings → Variables بوضع INFER_MODEL. الافتراضي:
33
- INFER_MODEL = os.environ.get("INFER_MODEL", "Qwen/Qwen2-VL-2B-Instruct")
34
 
35
  def get_infer_client():
36
  """تهيئة عميل الاستدلال مع مهلة أطول ورسالة واضحة إن غاب التوكين."""
@@ -44,10 +44,8 @@ def get_infer_client():
44
 
45
  def ocr_infer_api(pil_img: Image.Image) -> str:
46
  """
47
- نحاول بالترتيب:
48
- 1) visual_question_answering (VQA)
49
- 2) image_to_text بدون prompt
50
- 3) chat.completions مع data URI كحل أخير
51
  """
52
  try:
53
  client = get_infer_client()
@@ -55,62 +53,29 @@ def ocr_infer_api(pil_img: Image.Image) -> str:
55
  # حضّر الصورة كـ BytesIO
56
  buf = io.BytesIO()
57
  pil_img.save(buf, format="PNG")
58
- raw_bytes = buf.getvalue()
59
- b64 = base64.b64encode(raw_bytes).decode("utf-8")
60
 
61
- # --- المحاولة 1: VQA ---
62
  try:
63
- buf.seek(0)
64
- vqa_out = client.visual_question_answering(
65
- image=buf,
66
- question="اقرأ النص العربي في الصورة كما هو دون أي تغيير أو تعليق إضافي."
67
- )
68
- # بعض المزودين يرجعون list أو dict
69
- if isinstance(vqa_out, list):
70
- if vqa_out:
71
- if isinstance(vqa_out[0], dict) and "generated_text" in vqa_out[0]:
72
- txt = vqa_out[0]["generated_text"]
73
- else:
74
- txt = str(vqa_out[0])
75
- else:
76
- txt = ""
77
- else:
78
- txt = str(vqa_out)
79
- txt = (txt or "").strip()
80
  if txt:
81
  return txt
82
- except Exception:
83
- pass # ننتقل للمحاولة التالية
84
 
85
- # --- المحاولة 2: image_to_text (بدون prompt) ---
86
- last_err = None
 
87
  try:
88
- buf.seek(0)
89
- it_out = client.image_to_text(image=buf)
90
- it_txt = (it_out or "").strip()
91
- if it_txt:
92
- return it_txt
93
- except Exception as e_img2txt:
94
- last_err = e_img2txt # نحتفظ بآخر خطأ محتمل
95
 
96
- # --- المحاولة 3: chat.completions مع data URI ---
97
- try:
98
- messages = [
99
- {"role": "system", "content": "You are an OCR assistant. Return ONLY the Arabic text as-is."},
100
- {
101
- "role": "user",
102
- "content": [
103
- {"type": "input_text", "text": "Extract Arabic text exactly as-is, no extra commentary."},
104
- {"type": "image_url", "image_url": f"data:image/png;base64,{b64}"},
105
- ],
106
- },
107
- ]
108
- resp = client.chat.completions.create(messages=messages, max_tokens=2048)
109
- txt = resp.choices[0].message.content or ""
110
- return txt.strip()
111
- except Exception as e_chat:
112
- # إن فشل الجميع، نُظهر أوضح خطأ متاح
113
- return f"حدث خطأ أثناء استدعاء Inference API: {repr(last_err or e_chat)}"
114
 
115
  except Exception as e:
116
  return f"حدث خطأ أثناء استدعاء Inference API: {repr(e)}"
@@ -129,7 +94,7 @@ except Exception:
129
 
130
  _HOROOF_MODEL = None
131
  _HOROOF_PROC = None
132
- # يمكن تغيير اسم نموذجك من Settings → Variables بوضع HOROOF_MODEL:
133
  HOROOF_MODEL_NAME = os.environ.get("HOROOF_MODEL", "NaserNajeh/Horoof")
134
 
135
  def ensure_horoof_loaded():
@@ -225,8 +190,8 @@ def diag_infer():
225
  info.append(f"HTTP check error: {repr(e)}")
226
  try:
227
  client = get_infer_client()
228
- # ping بسيط
229
- resp = client.text_generation("ping", max_new_tokens=1)
230
  info.append("basic text_generation ping: OK")
231
  except Exception as e:
232
  info.append(f"text_generation ping error: {repr(e)}")
 
1
+ import os, io, base64, traceback, time
2
  import gradio as gr
3
  import fitz # PyMuPDF
4
  from PIL import Image
 
25
 
26
  # ===============================================
27
  # 2) Inference API (يستهلك اعتمادات PRO بدل دقائق GPU)
28
+ # نستخدم TrOCR عربي عبر image_to_text فقط
29
  # ===============================================
30
  from huggingface_hub import InferenceClient
31
  _INFER_CLIENT = None
32
+ # يمكنك تغييره من Settings → Variables بوضع INFER_MODEL، الافتراضي أدناه TrOCR عربي:
33
+ INFER_MODEL = os.environ.get("INFER_MODEL", "David-Magdy/TR_OCR_LARGE")
34
 
35
  def get_infer_client():
36
  """تهيئة عميل الاستدلال مع مهلة أطول ورسالة واضحة إن غاب التوكين."""
 
44
 
45
  def ocr_infer_api(pil_img: Image.Image) -> str:
46
  """
47
+ استدعاء Inference API لنموذج OCR عربي (TrOCR) عبر image_to_text فقط،
48
+ مع معالجة حالة التحميل/المهلة بإعادة محاولة واحدة.
 
 
49
  """
50
  try:
51
  client = get_infer_client()
 
53
  # حضّر الصورة كـ BytesIO
54
  buf = io.BytesIO()
55
  pil_img.save(buf, format="PNG")
56
+ buf.seek(0)
 
57
 
58
+ # المحاولة الأولى
59
  try:
60
+ out = client.image_to_text(image=buf)
61
+ txt = (out or "").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  if txt:
63
  return txt
64
+ except Exception as e1:
65
+ last = repr(e1)
66
 
67
+ # إعادة المحاولة (أحيانًا الموديل يكون في حالة "loading")
68
+ time.sleep(3)
69
+ buf.seek(0)
70
  try:
71
+ out = client.image_to_text(image=buf)
72
+ txt = (out or "").strip()
73
+ if txt:
74
+ return txt
75
+ except Exception as e2:
76
+ last = repr(e2)
 
77
 
78
+ return f"حدث خطأ أثناء استدعاء Inference API (image_to_text): {last}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  except Exception as e:
81
  return f"حدث خطأ أثناء استدعاء Inference API: {repr(e)}"
 
94
 
95
  _HOROOF_MODEL = None
96
  _HOROOF_PROC = None
97
+ # يمكنك تغييره من Settings → Variables بوضع HOROOF_MODEL:
98
  HOROOF_MODEL_NAME = os.environ.get("HOROOF_MODEL", "NaserNajeh/Horoof")
99
 
100
  def ensure_horoof_loaded():
 
190
  info.append(f"HTTP check error: {repr(e)}")
191
  try:
192
  client = get_infer_client()
193
+ # ping بسيط (قد يفشل لبعض النماذج؛ الهدف اختبار المصادقة والاتصال)
194
+ _ = client.text_generation("ping", max_new_tokens=1)
195
  info.append("basic text_generation ping: OK")
196
  except Exception as e:
197
  info.append(f"text_generation ping error: {repr(e)}")