kebson commited on
Commit
35f4e3c
·
verified ·
1 Parent(s): 4385c86

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -46
app.py CHANGED
@@ -1,77 +1,128 @@
1
  import os
 
2
  import pandas as pd
3
- from paddleocr import PaddleOCR
4
  import gradio as gr
 
5
 
6
- def extract_second_column(image_path, ocr):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  result = ocr.ocr(image_path, cls=True)
 
8
  if not result or not result[0]:
9
  return []
10
 
11
- boxes = result[0]
12
 
13
- boxes_sorted_x = sorted(
14
- boxes,
15
- key=lambda b: min(p[0] for p in b[0])
16
- )
17
 
18
- columns = {}
19
- for box in boxes_sorted_x:
20
- x_center = sum(p[0] for p in box[0]) / 4
21
- columns.setdefault(int(x_center // 120), []).append(box)
22
 
23
- if len(columns) < 2:
24
- return []
 
 
25
 
26
- sorted_cols = sorted(columns.items())
27
- second_col = sorted_cols[1][1]
28
 
29
- second_col = sorted(
30
- second_col,
31
- key=lambda b: min(p[1] for p in b[0])
32
- )
33
 
34
- return [b[1][0] for b in second_col]
 
 
 
 
 
35
 
36
- def run_ocr():
 
 
 
 
 
 
 
37
  images_dir = "images"
38
- output_dir = "/data"
39
- os.makedirs(output_dir, exist_ok=True)
40
-
41
- # ⚠️ OCR INITIALISÉ ICI (PAS AU DÉMARRAGE)
42
- ocr = PaddleOCR(
43
- use_angle_cls=True,
44
- lang="fr",
45
- show_log=False,
46
- cpu_threads=1
47
- )
48
 
49
  all_results = []
50
 
51
  for filename in sorted(os.listdir(images_dir)):
52
  if filename.lower().endswith((".jpg", ".jpeg", ".png")):
53
  image_path = os.path.join(images_dir, filename)
54
- values = extract_second_column(image_path, ocr)
55
 
56
- for v in values:
57
  all_results.append({
58
  "image": filename,
59
- "colonne_2": v
60
  })
61
 
 
 
 
62
  df = pd.DataFrame(all_results)
63
- output_path = os.path.join(output_dir, "resultats_colonne_2.csv")
64
- df.to_csv(output_path, index=False,sep=";",encoding="utf-8-sig")
65
-
66
- return output_path
67
-
68
- gr.Interface(
69
- fn=run_ocr,
70
- inputs=[],
71
- outputs=gr.File(label="Télécharger le CSV"),
72
- title="Extraction OCR Colonne 2",
73
- description="Cliquez pour lancer l'OCR (première exécution plus lente)"
74
- ).launch(server_name="0.0.0.0",server_port=7860,allowed_paths=["/data"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
 
77
 
 
1
  import os
2
+ import re
3
  import pandas as pd
 
4
  import gradio as gr
5
+ from paddleocr import PaddleOCR
6
 
7
+ # =============================
8
+ # Initialisation OCR
9
+ # =============================
10
+ ocr = PaddleOCR(
11
+ lang="fr",
12
+ use_angle_cls=True,
13
+ show_log=False
14
+ )
15
+
16
+ # =============================
17
+ # Fonctions utilitaires
18
+ # =============================
19
+
20
+ def is_textual(text):
21
+ """
22
+ Retourne True si le texte contient au moins une lettre
23
+ (donc pas uniquement des chiffres ou montants)
24
+ """
25
+ text = text.strip()
26
+ return bool(re.search(r"[A-Za-zÀ-ÿ]", text))
27
+
28
+
29
+ def extract_second_column_text(image_path):
30
+ """
31
+ Extrait les textes OCR situés dans la 2ᵉ colonne logique
32
+ et conserve uniquement les textes (pas de chiffres)
33
+ """
34
  result = ocr.ocr(image_path, cls=True)
35
+
36
  if not result or not result[0]:
37
  return []
38
 
39
+ elements = []
40
 
41
+ # Collecte des boxes et textes
42
+ for line in result[0]:
43
+ box = line[0]
44
+ text = line[1][0]
45
 
46
+ # position X moyenne du bloc
47
+ x_center = sum([p[0] for p in box]) / 4
 
 
48
 
49
+ elements.append({
50
+ "x": x_center,
51
+ "text": text.strip()
52
+ })
53
 
54
+ # Trier par position horizontale
55
+ elements = sorted(elements, key=lambda x: x["x"])
56
 
57
+ # Supposer que la 1ʳᵉ colonne est la plus à gauche
58
+ min_x = elements[0]["x"]
 
 
59
 
60
+ # Tout ce qui est suffisamment à droite = colonne 2
61
+ column_2 = [
62
+ e["text"]
63
+ for e in elements
64
+ if e["x"] > min_x + 50 and is_textual(e["text"])
65
+ ]
66
 
67
+ return column_2
68
+
69
+
70
+ # =============================
71
+ # Fonction principale
72
+ # =============================
73
+
74
+ def run_extraction():
75
  images_dir = "images"
76
+
77
+ if not os.path.exists(images_dir):
78
+ return "❌ Dossier 'images' introuvable", None
 
 
 
 
 
 
 
79
 
80
  all_results = []
81
 
82
  for filename in sorted(os.listdir(images_dir)):
83
  if filename.lower().endswith((".jpg", ".jpeg", ".png")):
84
  image_path = os.path.join(images_dir, filename)
85
+ texts = extract_second_column_text(image_path)
86
 
87
+ for t in texts:
88
  all_results.append({
89
  "image": filename,
90
+ "colonne_2": t
91
  })
92
 
93
+ if not all_results:
94
+ return "⚠️ Aucun texte détecté", None
95
+
96
  df = pd.DataFrame(all_results)
97
+
98
+ output_path = "/tmp/resultats_colonne_2.csv"
99
+ df.to_csv(
100
+ output_path,
101
+ index=False,
102
+ sep=";",
103
+ encoding="utf-8-sig"
104
+ )
105
+
106
+ return "Extraction terminée avec succès", output_path
107
+
108
+
109
+ # =============================
110
+ # Interface Gradio
111
+ # =============================
112
+
113
+ with gr.Blocks(title="Extraction OCR – Colonne 2") as demo:
114
+ gr.Markdown("## 📄 Extraction de la 2ᵉ colonne (texte uniquement)")
115
+
116
+ run_btn = gr.Button("🔍 Lancer l'extraction")
117
+ status = gr.Textbox(label="Statut")
118
+ file_out = gr.File(label="Télécharger le CSV")
119
+
120
+ run_btn.click(
121
+ fn=run_extraction,
122
+ outputs=[status, file_out]
123
+ )
124
+
125
+ demo.launch()
126
 
127
 
128