Asem75 commited on
Commit
e1bf556
·
verified ·
1 Parent(s): d7dd869

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -160
app.py CHANGED
@@ -2,58 +2,31 @@ import os
2
  import time
3
  import threading
4
  import tempfile
5
- import subprocess
6
- import shutil
7
  import gradio as gr
8
  from huggingface_hub import HfApi, hf_hub_download, login
9
  from PIL import Image
10
  import fitz # PyMuPDF
 
11
 
12
  # =====================================================
13
- # 1️⃣ إعداد مسار Tesseract بشكل صريح (الإصلاح الرئيسي)
14
  # =====================================================
15
- def setup_tesseract():
16
- """البحث عن Tesseract وتعيين مساره صراحةً"""
17
- import pytesseract
18
-
19
- possible_paths = [
20
- "/usr/bin/tesseract",
21
- "/usr/local/bin/tesseract",
22
- "/opt/homebrew/bin/tesseract",
23
- ]
24
-
25
- # محاولة إيجاد المسار تلقائياً
26
- found = shutil.which("tesseract")
27
- if found:
28
- pytesseract.pytesseract.tesseract_cmd = found
29
- print(f"✅ Tesseract وُجد في: {found}")
30
- return True
31
-
32
- for path in possible_paths:
33
- if os.path.isfile(path):
34
- pytesseract.pytesseract.tesseract_cmd = path
35
- print(f"✅ Tesseract وُجد في: {path}")
36
- return True
37
-
38
- # محاولة التثبيت الآني كملاذ أخير
39
- print("⚠️ Tesseract غير موجود، محاولة تثبيته...")
40
- try:
41
- subprocess.run(
42
- ["apt-get", "install", "-y", "--no-install-recommends",
43
- "tesseract-ocr", "tesseract-ocr-ara", "tesseract-ocr-eng"],
44
- check=True, capture_output=True
45
- )
46
- found = shutil.which("tesseract")
47
- if found:
48
- pytesseract.pytesseract.tesseract_cmd = found
49
- print(f"✅ تم تثبيت Tesseract في: {found}")
50
- return True
51
- except Exception as e:
52
- print(f"❌ فشل التثبيت التلقائي: {e}")
53
-
54
- return False
55
-
56
- TESSERACT_OK = setup_tesseract()
57
 
58
  # =====================================================
59
  # 2️⃣ إعدادات المستودع
@@ -71,86 +44,82 @@ RAW_DIR = "raw_files"
71
  PROCESS_DIR = "process_files"
72
  SUPPORTED = {".pdf", ".png", ".jpg", ".jpeg"}
73
 
74
- # متغيرات للمراقبة
75
- engine_status = {"last": "🟡 يبدأ التشغيل...", "processed": 0, "errors": 0}
 
 
 
 
76
 
77
  # =====================================================
78
- # 3️⃣ محرك OCR
79
  # =====================================================
80
- def perform_ocr_on_image(img: Image.Image) -> str:
81
- """استخراج النص من صورة مع دعم الخط اليدوي"""
82
- import pytesseract
83
-
84
- configs = [
85
- "--oem 1 --psm 3", # وضع عادي - LSTM
86
- "--oem 1 --psm 6", # كتلة نصية موحدة
87
- "--oem 1 --psm 7", # سطر واحد (مفيد للخط اليدوي)
88
- "--oem 1 --psm 11", # نص متفرق
89
- ]
90
-
91
- best_text = ""
92
- for cfg in configs:
93
- try:
94
- text = pytesseract.image_to_string(img, lang="ara+eng", config=cfg)
95
- if len(text.strip()) > len(best_text.strip()):
96
- best_text = text
97
- except Exception:
98
- continue
99
-
100
- return best_text.strip()
101
 
102
 
103
- def perform_ocr_on_file(local_path: str) -> str:
104
  """استخراج النص من صورة أو PDF"""
105
  ext = os.path.splitext(local_path)[1].lower()
106
- extracted_parts = []
107
 
108
  try:
109
  if ext in {".png", ".jpg", ".jpeg"}:
110
- img = Image.open(local_path).convert("RGB")
111
- text = perform_ocr_on_image(img)
112
  if text:
113
- extracted_parts.append(text)
114
 
115
  elif ext == ".pdf":
116
  doc = fitz.open(local_path)
117
  for page_num in range(len(doc)):
118
- page = doc[page_num]
 
119
 
120
- # أولاً: محاولة استخراج النص المُضمَّن
121
- embedded = page.get_text("text").strip()
122
- if embedded:
123
- extracted_parts.append(f"--- صفحة {page_num + 1} ---\n{embedded}")
124
- continue
125
 
126
- # ثانياً: تحويل الصفحة إلى صورة وتطبيق OCR
127
- pix = page.get_pixmap(dpi=300)
128
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tf:
129
- img_path = tf.name
130
- pix.save(img_path)
131
 
132
- try:
133
- img = Image.open(img_path).convert("RGB")
134
- ocr_text = perform_ocr_on_image(img)
 
 
135
  if ocr_text:
136
- extracted_parts.append(f"--- صفحة {page_num + 1} (OCR) ---\n{ocr_text}")
137
- finally:
138
- if os.path.exists(img_path):
139
- os.remove(img_path)
 
140
 
141
  doc.close()
142
 
143
  except Exception as e:
144
- print(f"❌ خطأ في OCR: {e}")
145
 
146
- return "\n\n".join(extracted_parts).strip()
147
 
148
 
149
  # =====================================================
150
- # 4️⃣ رفع نتيجة مع إعادة المحاولة عند Rate Limit
151
  # =====================================================
152
  def safe_upload(tmp_path: str, dest_path: str, commit_msg: str, retries: int = 5) -> bool:
153
- """رفع ملف مع معالجة Rate Limit"""
154
  for attempt in range(retries):
155
  try:
156
  api.upload_file(
@@ -164,18 +133,16 @@ def safe_upload(tmp_path: str, dest_path: str, commit_msg: str, retries: int = 5
164
  return True
165
  except Exception as e:
166
  err = str(e).lower()
 
167
  if "rate limit" in err or "429" in err:
168
- wait = 30 * (attempt + 1)
169
- print(f"⏳ Rate Limit - انتظار {wait} ثانية...")
170
- time.sleep(wait)
171
  else:
172
- print(f"❌ خطأ في الرفع (محاولة {attempt + 1}): {e}")
173
- time.sleep(5)
174
  return False
175
 
176
 
177
  def safe_delete(file_path: str, retries: int = 3) -> bool:
178
- """حذف ملف مع معالجة الأخطاء"""
179
  for attempt in range(retries):
180
  try:
181
  api.delete_file(
@@ -190,24 +157,22 @@ def safe_delete(file_path: str, retries: int = 3) -> bool:
190
  if "rate limit" in err or "429" in err:
191
  time.sleep(30)
192
  else:
193
- print(f"❌ خطأ في الحذف: {e}")
194
  time.sleep(5)
195
  return False
196
 
197
 
198
  # =====================================================
199
- # 5️⃣ حلقة الخلفية الرئيسية
200
  # =====================================================
201
  def sapphire_background_pulse():
202
- global engine_status
203
- print("🔮 محرك Sapphire OCR يعمل في الخلفية...")
204
 
205
  while True:
206
  local_path = None
207
  try:
208
- # جلب قائمة الملفات
209
- all_files = api.list_repo_files(REPO_ID, repo_type="dataset")
210
- raw_items = [
211
  f for f in all_files
212
  if f.startswith(RAW_DIR + "/")
213
  and os.path.splitext(f)[1].lower() in SUPPORTED
@@ -218,12 +183,17 @@ def sapphire_background_pulse():
218
  time.sleep(15)
219
  continue
220
 
 
 
 
 
 
 
221
  target = raw_items[0]
222
  filename = os.path.basename(target)
223
  engine_status["last"] = f"⚙️ يعالج: {filename}"
224
  print(f"\n📥 تنزيل: {filename}")
225
 
226
- # تنزيل الملف
227
  local_path = hf_hub_download(
228
  repo_id=REPO_ID,
229
  filename=target,
@@ -232,68 +202,58 @@ def sapphire_background_pulse():
232
  force_download=True,
233
  )
234
 
235
- # التحقق من Tesseract قبل المعالجة
236
- if not TESSERACT_OK:
237
- engine_status["last"] = "❌ Tesseract غير مثبت!"
238
- engine_status["errors"] += 1
239
- time.sleep(60)
240
- continue
241
-
242
- # استخراج النص
243
- extracted_text = perform_ocr_on_file(local_path)
244
 
245
- if extracted_text:
246
- # حفظ النص وقتياً
247
  with tempfile.NamedTemporaryFile(
248
  mode="w", suffix=".txt", delete=False, encoding="utf-8"
249
  ) as tmp:
250
- tmp.write(extracted_text)
251
  tmp_path = tmp.name
252
 
253
  dest_name = os.path.splitext(filename)[0] + "_extracted.txt"
254
  dest_path = f"{PROCESS_DIR}/{dest_name}"
255
 
256
- # رفع النتيجة
257
  uploaded = safe_upload(
258
- tmp_path,
259
- dest_path,
260
- commit_msg=f"OCR ✅ {filename}",
261
  )
262
  os.unlink(tmp_path)
263
 
264
  if uploaded:
265
- # حذف الملف الخام فقط بعد نجاح الرفع
266
  deleted = safe_delete(target)
267
- status_msg = (
268
- f"✅ [{time.strftime('%H:%M:%S')}] {filename} → {dest_name}"
 
 
269
  )
270
- engine_status["last"] = status_msg
271
  engine_status["processed"] += 1
272
- print(status_msg + (" (الأصل محذوف)" if deleted else " (⚠️ الأصل لم يُحذف)"))
273
  else:
274
  engine_status["errors"] += 1
275
- engine_status["last"] = f"❌ فشل رفع {dest_name}"
276
  else:
277
  engine_status["last"] = f"⚠️ لم يُستخرج نص من {filename}"
278
  engine_status["errors"] += 1
279
- print(f"⚠️ لا نص في {filename} - يبقى في raw_files")
280
 
281
  time.sleep(3)
282
 
283
  except Exception as e:
284
  err_msg = str(e)
285
- print(f"⚠️ خطأ في المحرك: {err_msg}")
286
  engine_status["errors"] += 1
 
287
 
288
  if "rate limit" in err_msg.lower() or "429" in err_msg:
289
- engine_status["last"] = "⏳ Rate Limit - انتظار 60 ثانية..."
290
  time.sleep(60)
291
  else:
292
- engine_status["last"] = f"⚠️ خطأ: {err_msg[:80]}"
293
  time.sleep(20)
294
 
295
  finally:
296
- # تنظيف الملف المحلي المؤقت
297
  if local_path and os.path.exists(local_path):
298
  try:
299
  os.remove(local_path)
@@ -301,24 +261,28 @@ def sapphire_background_pulse():
301
  pass
302
 
303
 
304
- # تشغيل المحرك في خيط مستقل
305
  threading.Thread(target=sapphire_background_pulse, daemon=True).start()
306
 
307
 
308
  # =====================================================
309
- # 6️⃣ واجهة Gradio للمراقبة
310
  # =====================================================
311
  custom_css = """
312
  body, .gradio-container { background-color: #0a0a0a !important; color: #e0e0e0 !important; }
313
- .stat-box { background: #1a1a2e; border: 1px solid #d4af37; border-radius: 8px;
314
- padding: 12px; margin: 6px; text-align: center; }
315
  """
316
 
317
- with gr.Blocks(css=custom_css, title="Sapphire OCR Engine") as demo:
 
 
 
 
 
 
 
318
  gr.Markdown("# 🔮 محرك Sapphire OCR — لوحة المراقبة")
319
  gr.Markdown(
320
  f"**المستودع:** `{REPO_ID}` | "
321
- f"**Tesseract:** {'✅ مثبت' if TESSERACT_OK else '❌ غير مثبت'}"
322
  )
323
 
324
  with gr.Row():
@@ -326,30 +290,22 @@ with gr.Blocks(css=custom_css, title="Sapphire OCR Engine") as demo:
326
  label="آخر عملية",
327
  value="🟡 يبدأ...",
328
  interactive=False,
329
- elem_classes=["status_text"],
330
  )
331
-
332
  with gr.Row():
333
  processed_box = gr.Number(label="✅ الملفات المعالجة", value=0, interactive=False)
334
  errors_box = gr.Number(label="❌ الأخطاء", value=0, interactive=False)
335
 
336
  refresh_btn = gr.Button("🔄 تحديث الحالة", variant="secondary")
 
337
 
338
- def get_status():
339
- return (
340
- engine_status["last"],
341
- engine_status["processed"],
342
- engine_status["errors"],
343
- )
344
-
345
- refresh_btn.click(
346
- fn=get_status,
347
- outputs=[status_box, processed_box, errors_box],
348
- )
349
-
350
- # تحديث تلقائي كل 10 ثوانٍ
351
- demo.load(fn=get_status, outputs=[status_box, processed_box, errors_box], every=10)
352
 
353
 
354
  if __name__ == "__main__":
355
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
2
  import time
3
  import threading
4
  import tempfile
 
 
5
  import gradio as gr
6
  from huggingface_hub import HfApi, hf_hub_download, login
7
  from PIL import Image
8
  import fitz # PyMuPDF
9
+ import numpy as np
10
 
11
  # =====================================================
12
+ # 1️⃣ تهيئة EasyOCR (بديل Tesseract - لا يحتاج تثبيت نظام)
13
  # =====================================================
14
+ print("🔄 تحميل نموذج EasyOCR للعربية... (قد يستغرق دقيقة)")
15
+ try:
16
+ import easyocr
17
+ # تحميل النموذج مرة واحدة عند البدء
18
+ OCR_READER = easyocr.Reader(
19
+ ["ar", "en"],
20
+ gpu=False,
21
+ model_storage_directory="/tmp/easyocr_models",
22
+ download_enabled=True,
23
+ )
24
+ OCR_OK = True
25
+ print("✅ EasyOCR جاهز للعمل")
26
+ except Exception as e:
27
+ OCR_OK = False
28
+ OCR_READER = None
29
+ print(f"❌ فشل تحميل EasyOCR: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  # =====================================================
32
  # 2️⃣ إعدادات المستودع
 
44
  PROCESS_DIR = "process_files"
45
  SUPPORTED = {".pdf", ".png", ".jpg", ".jpeg"}
46
 
47
+ # متغيرات المراقبة
48
+ engine_status = {
49
+ "last": "🟡 يبدأ التشغيل...",
50
+ "processed": 0,
51
+ "errors": 0,
52
+ }
53
 
54
  # =====================================================
55
+ # 3️⃣ دوال OCR باستخدام EasyOCR
56
  # =====================================================
57
+ def ocr_image(pil_img: Image.Image) -> str:
58
+ """استخراج النص من صورة PIL باستخدام EasyOCR"""
59
+ if not OCR_OK or OCR_READER is None:
60
+ return ""
61
+ try:
62
+ # تحويل الصورة إلى numpy array
63
+ img_array = np.array(pil_img.convert("RGB"))
64
+ results = OCR_READER.readtext(img_array, detail=0, paragraph=True)
65
+ return "\n".join(results).strip()
66
+ except Exception as e:
67
+ print(f"❌ خطأ OCR على صورة: {e}")
68
+ return ""
 
 
 
 
 
 
 
 
 
69
 
70
 
71
+ def extract_from_file(local_path: str) -> str:
72
  """استخراج النص من صورة أو PDF"""
73
  ext = os.path.splitext(local_path)[1].lower()
74
+ parts = []
75
 
76
  try:
77
  if ext in {".png", ".jpg", ".jpeg"}:
78
+ img = Image.open(local_path)
79
+ text = ocr_image(img)
80
  if text:
81
+ parts.append(text)
82
 
83
  elif ext == ".pdf":
84
  doc = fitz.open(local_path)
85
  for page_num in range(len(doc)):
86
+ try:
87
+ page = doc[page_num]
88
 
89
+ # محاولة 1: نص مُضمَّن
90
+ embedded = page.get_text("text").strip()
91
+ if embedded and len(embedded) > 10:
92
+ parts.append(f"--- صفحة {page_num + 1} ---\n{embedded}")
93
+ continue
94
 
95
+ # محاولة 2: تحويل إلى صورة → OCR
96
+ mat = fitz.Matrix(2.0, 2.0) # دقة ×2
97
+ pix = page.get_pixmap(matrix=mat)
 
 
98
 
99
+ img_data = pix.tobytes("png")
100
+ import io
101
+ img = Image.open(io.BytesIO(img_data)).convert("RGB")
102
+
103
+ ocr_text = ocr_image(img)
104
  if ocr_text:
105
+ parts.append(f"--- صفحة {page_num + 1} (OCR) ---\n{ocr_text}")
106
+
107
+ except Exception as page_err:
108
+ print(f"⚠️ خطأ في صفحة {page_num + 1}: {page_err}")
109
+ continue
110
 
111
  doc.close()
112
 
113
  except Exception as e:
114
+ print(f"❌ خطأ في استخراج الملف: {e}")
115
 
116
+ return "\n\n".join(parts).strip()
117
 
118
 
119
  # =====================================================
120
+ # 4️⃣ رفع وحذف مع معالجة Rate Limit
121
  # =====================================================
122
  def safe_upload(tmp_path: str, dest_path: str, commit_msg: str, retries: int = 5) -> bool:
 
123
  for attempt in range(retries):
124
  try:
125
  api.upload_file(
 
133
  return True
134
  except Exception as e:
135
  err = str(e).lower()
136
+ wait = 30 * (attempt + 1)
137
  if "rate limit" in err or "429" in err:
138
+ print(f"⏳ Rate Limit - انتظار {wait}s (محاولة {attempt+1})")
 
 
139
  else:
140
+ print(f"❌ رفع فاشل (محاولة {attempt+1}): {e}")
141
+ time.sleep(wait)
142
  return False
143
 
144
 
145
  def safe_delete(file_path: str, retries: int = 3) -> bool:
 
146
  for attempt in range(retries):
147
  try:
148
  api.delete_file(
 
157
  if "rate limit" in err or "429" in err:
158
  time.sleep(30)
159
  else:
160
+ print(f"❌ حذف فاشل: {e}")
161
  time.sleep(5)
162
  return False
163
 
164
 
165
  # =====================================================
166
+ # 5️⃣ حلقة الخلفية
167
  # =====================================================
168
  def sapphire_background_pulse():
169
+ print("🔮 محرك Sapphire OCR (EasyOCR) يعمل...")
 
170
 
171
  while True:
172
  local_path = None
173
  try:
174
+ all_files = list(api.list_repo_files(REPO_ID, repo_type="dataset"))
175
+ raw_items = [
 
176
  f for f in all_files
177
  if f.startswith(RAW_DIR + "/")
178
  and os.path.splitext(f)[1].lower() in SUPPORTED
 
183
  time.sleep(15)
184
  continue
185
 
186
+ if not OCR_OK:
187
+ engine_status["last"] = "❌ EasyOCR غير جاهز - تحقق من السجلات"
188
+ engine_status["errors"] += 1
189
+ time.sleep(60)
190
+ continue
191
+
192
  target = raw_items[0]
193
  filename = os.path.basename(target)
194
  engine_status["last"] = f"⚙️ يعالج: {filename}"
195
  print(f"\n📥 تنزيل: {filename}")
196
 
 
197
  local_path = hf_hub_download(
198
  repo_id=REPO_ID,
199
  filename=target,
 
202
  force_download=True,
203
  )
204
 
205
+ print(f"🔍 استخراج النص من: {filename}")
206
+ extracted = extract_from_file(local_path)
 
 
 
 
 
 
 
207
 
208
+ if extracted:
 
209
  with tempfile.NamedTemporaryFile(
210
  mode="w", suffix=".txt", delete=False, encoding="utf-8"
211
  ) as tmp:
212
+ tmp.write(extracted)
213
  tmp_path = tmp.name
214
 
215
  dest_name = os.path.splitext(filename)[0] + "_extracted.txt"
216
  dest_path = f"{PROCESS_DIR}/{dest_name}"
217
 
 
218
  uploaded = safe_upload(
219
+ tmp_path, dest_path,
220
+ commit_msg=f"OCR ✅ {filename}"
 
221
  )
222
  os.unlink(tmp_path)
223
 
224
  if uploaded:
 
225
  deleted = safe_delete(target)
226
+ msg = (
227
+ f"✅ [{time.strftime('%H:%M:%S')}] "
228
+ f"{filename} → {dest_name}"
229
+ f"{' 🗑️' if deleted else ' ⚠️ الأصل لم يُحذف'}"
230
  )
231
+ engine_status["last"] = msg
232
  engine_status["processed"] += 1
233
+ print(msg)
234
  else:
235
  engine_status["errors"] += 1
236
+ engine_status["last"] = f"❌ فشل رفع نتيجة {filename}"
237
  else:
238
  engine_status["last"] = f"⚠️ لم يُستخرج نص من {filename}"
239
  engine_status["errors"] += 1
240
+ print(f"⚠️ لا نص مستخرج - يبقى الملف في raw_files")
241
 
242
  time.sleep(3)
243
 
244
  except Exception as e:
245
  err_msg = str(e)
 
246
  engine_status["errors"] += 1
247
+ print(f"⚠️ خطأ في المحرك: {err_msg}")
248
 
249
  if "rate limit" in err_msg.lower() or "429" in err_msg:
250
+ engine_status["last"] = "⏳ Rate Limit - انتظار 60s"
251
  time.sleep(60)
252
  else:
253
+ engine_status["last"] = f"⚠️ {err_msg[:80]}"
254
  time.sleep(20)
255
 
256
  finally:
 
257
  if local_path and os.path.exists(local_path):
258
  try:
259
  os.remove(local_path)
 
261
  pass
262
 
263
 
 
264
  threading.Thread(target=sapphire_background_pulse, daemon=True).start()
265
 
266
 
267
  # =====================================================
268
+ # 6️⃣ واجهة Gradio 6.x المُصلَّحة
269
  # =====================================================
270
  custom_css = """
271
  body, .gradio-container { background-color: #0a0a0a !important; color: #e0e0e0 !important; }
 
 
272
  """
273
 
274
+ def get_status():
275
+ return (
276
+ engine_status["last"],
277
+ float(engine_status["processed"]),
278
+ float(engine_status["errors"]),
279
+ )
280
+
281
+ with gr.Blocks(title="Sapphire OCR Engine") as demo:
282
  gr.Markdown("# 🔮 محرك Sapphire OCR — لوحة المراقبة")
283
  gr.Markdown(
284
  f"**المستودع:** `{REPO_ID}` | "
285
+ f"**EasyOCR:** {'✅ جاهز' if OCR_OK else '❌ غير جاهز'}"
286
  )
287
 
288
  with gr.Row():
 
290
  label="آخر عملية",
291
  value="🟡 يبدأ...",
292
  interactive=False,
 
293
  )
 
294
  with gr.Row():
295
  processed_box = gr.Number(label="✅ الملفات المعالجة", value=0, interactive=False)
296
  errors_box = gr.Number(label="❌ الأخطاء", value=0, interactive=False)
297
 
298
  refresh_btn = gr.Button("🔄 تحديث الحالة", variant="secondary")
299
+ refresh_btn.click(fn=get_status, outputs=[status_box, processed_box, errors_box])
300
 
301
+ # تحديث تلقائي - صيغة Gradio 6.x
302
+ timer = gr.Timer(value=10)
303
+ timer.tick(fn=get_status, outputs=[status_box, processed_box, errors_box])
 
 
 
 
 
 
 
 
 
 
 
304
 
305
 
306
  if __name__ == "__main__":
307
+ demo.launch(
308
+ server_name="0.0.0.0",
309
+ server_port=7860,
310
+ css=custom_css, # ← انتقل إلى launch() في Gradio 6
311
+ )