Skander453 commited on
Commit
a3f3288
Β·
verified Β·
1 Parent(s): fd40321

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -88
app.py CHANGED
@@ -2,93 +2,57 @@ import gradio as gr
2
  import easyocr
3
  from transformers import pipeline
4
  import numpy as np
 
5
  from docx import Document
6
  from pptx import Presentation
7
  import os
8
- from PIL import Image
9
 
10
- # Initialisation du lecteur EasyOCR (anglais par dΓ©faut)
11
- reader = easyocr.Reader(['en','fr'], gpu=False)
12
 
13
- # Initialisation du pipeline de rΓ©sumΓ© (BART)
14
  summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
15
 
16
- def extraire_et_resumer(image):
17
- """
18
- Extraire le texte d'une image avec EasyOCR et le rΓ©sumer avec BART
19
-
20
- Args:
21
- image: image PIL ou tableau numpy
22
-
23
- Returns:
24
- tuple: (texte_extrait, texte_resume)
25
- """
26
  try:
27
- # Convertir l'image PIL en numpy si nΓ©cessaire
28
  if isinstance(image, Image.Image):
29
  image = np.array(image)
30
 
31
- # OCR avec EasyOCR
32
- results = reader.readtext(image)
33
-
34
- # Combiner le texte extrait
35
- texte_extrait = " ".join([result[1] for result in results])
36
-
37
- if not texte_extrait.strip():
38
- return "Aucun texte dΓ©tectΓ© dans l'image.", "Aucun texte Γ  rΓ©sumer."
39
-
40
- # VΓ©rifier le nombre de mots
41
- nombre_mots = len(texte_extrait.split())
42
-
43
- if nombre_mots < 30:
44
- return texte_extrait, "Le texte est trop court pour Γͺtre rΓ©sumΓ© (minimum 30 mots)."
45
-
46
- # Paramètres du résumé
47
- max_length = min(150, nombre_mots)
48
- min_length = min(30, nombre_mots // 2)
49
-
50
- # RΓ©sumΓ©
51
- resume = summarizer(
52
- if not text or len(text.split()) < 30:
53
- return "Texte trop court pour Γͺtre rΓ©sumΓ©."
54
 
55
- max_length = min(150, len(text.split()))
56
- min_length = min(30, len(text.split()) // 2)
57
 
58
- summary = summarizer(
59
- text,
60
- max_length=max_length,
61
- min_length=min_length,
62
- do_sample=False
63
- )
64
-
65
- return summary[0]["summary_text"]
66
 
 
 
 
 
 
 
67
  )
68
 
69
- texte_resume = resume[0]["summary_text"]
70
-
71
- return texte_extrait, texte_resume
72
 
73
  except Exception as e:
74
- return f"Erreur : {str(e)}", "Impossible de gΓ©nΓ©rer le rΓ©sumΓ©."
75
-
76
-
77
 
 
78
  def extract_text_from_file(file_path):
79
  ext = os.path.splitext(file_path)[1].lower()
80
 
81
- # TXT
82
  if ext == ".txt":
83
  with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
84
  return f.read()
85
 
86
- # WORD
87
  elif ext == ".docx":
88
  doc = Document(file_path)
89
- return "\n".join([p.text for p in doc.paragraphs])
90
 
91
- # POWERPOINT
92
  elif ext == ".pptx":
93
  prs = Presentation(file_path)
94
  text = []
@@ -101,44 +65,67 @@ def extract_text_from_file(file_path):
101
  else:
102
  return ""
103
 
104
- # Interface Gradio
105
- with gr.Blocks(title="OCR & Text Summarizer") as demo:
106
- gr.Markdown("""
107
- # πŸ“ OCR & RΓ©sumΓ© de texte
108
- TΓ©lΓ©verse une image contenant du texte :
109
- 1. Le texte est extrait avec EasyOCR
110
- 2. Il est rΓ©sumΓ© avec une IA (BART)
111
 
112
- **Minimum : 30 mots pour le rΓ©sumΓ©**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  """)
114
 
115
- with gr.Row():
116
- with gr.Column():
117
- file_input = gr.File(
118
- label="TΓ©lΓ©verser un fichier (TXT, DOCX, PPTX)",
119
- file_types=[".txt", ".docx", ".pptx"]
120
- )
121
 
 
 
 
 
 
 
 
 
 
 
 
122
  )
123
- submit_btn = gr.Button("Extraire et rΓ©sumer", variant="primary")
124
 
125
- with gr.Column():
126
- sortie_texte = gr.Textbox(
127
- label="Texte extrait",
128
- lines=10
 
129
  )
130
- sortie_resume = gr.Textbox(
131
- label="RΓ©sumΓ©",
132
- lines=5
 
 
 
 
 
133
  )
134
 
135
- submit_btn.click(
136
- fn=process_file,
137
- inputs=file_input,
138
- outputs=[sortie_texte, sortie_resume]
139
- )
140
-
141
-
142
- # Lancer l'application
143
  if __name__ == "__main__":
144
  demo.launch()
 
2
  import easyocr
3
  from transformers import pipeline
4
  import numpy as np
5
+ from PIL import Image
6
  from docx import Document
7
  from pptx import Presentation
8
  import os
 
9
 
10
+ # OCR (fr + en)
11
+ reader = easyocr.Reader(["fr", "en"], gpu=False)
12
 
13
+ # RΓ©sumΓ© BART
14
  summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
15
 
16
+ # ---------- IMAGE (OCR) ----------
17
+ def process_image(image):
 
 
 
 
 
 
 
 
18
  try:
 
19
  if isinstance(image, Image.Image):
20
  image = np.array(image)
21
 
22
+ results = reader.readtext(image, paragraph=True)
23
+ text = " ".join([r[1] for r in results])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ if not text.strip():
26
+ return "Aucun texte dΓ©tectΓ©.", "RΓ©sumΓ© impossible."
27
 
28
+ if len(text.split()) < 30:
29
+ return text, "Texte trop court pour Γͺtre rΓ©sumΓ©."
 
 
 
 
 
 
30
 
31
+ wc = len(text.split())
32
+ summary = summarizer(
33
+ text,
34
+ max_length=min(150, wc),
35
+ min_length=min(30, wc // 2),
36
+ do_sample=False
37
  )
38
 
39
+ return text, summary[0]["summary_text"]
 
 
40
 
41
  except Exception as e:
42
+ return f"Erreur : {e}", "Erreur."
 
 
43
 
44
+ # ---------- FICHIER ----------
45
  def extract_text_from_file(file_path):
46
  ext = os.path.splitext(file_path)[1].lower()
47
 
 
48
  if ext == ".txt":
49
  with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
50
  return f.read()
51
 
 
52
  elif ext == ".docx":
53
  doc = Document(file_path)
54
+ return "\n".join(p.text for p in doc.paragraphs)
55
 
 
56
  elif ext == ".pptx":
57
  prs = Presentation(file_path)
58
  text = []
 
65
  else:
66
  return ""
67
 
68
+ def process_file(file):
69
+ try:
70
+ text = extract_text_from_file(file.name)
71
+
72
+ if not text.strip():
73
+ return "Aucun texte dΓ©tectΓ©.", "RΓ©sumΓ© impossible."
 
74
 
75
+ if len(text.split()) < 30:
76
+ return text, "Texte trop court pour Γͺtre rΓ©sumΓ©."
77
+
78
+ wc = len(text.split())
79
+ summary = summarizer(
80
+ text,
81
+ max_length=min(150, wc),
82
+ min_length=min(30, wc // 2),
83
+ do_sample=False
84
+ )
85
+
86
+ return text, summary[0]["summary_text"]
87
+
88
+ except Exception as e:
89
+ return f"Erreur : {e}", "Erreur."
90
+
91
+ # ---------- INTERFACE ----------
92
+ with gr.Blocks(title="OCR & RΓ©sumΓ© (Image + Fichier)") as demo:
93
+ gr.Markdown("""
94
+ # 🧠 OCR & Résumé intelligent
95
+ - πŸ–ΌοΈ Images : OCR + rΓ©sumΓ©
96
+ - πŸ“„ Fichiers : TXT / DOCX / PPTX
97
  """)
98
 
99
+ with gr.Tabs():
 
 
 
 
 
100
 
101
+ # ----- TAB IMAGE -----
102
+ with gr.Tab("πŸ–ΌοΈ Image (OCR)"):
103
+ img_input = gr.Image(type="pil", label="TΓ©lΓ©verser une image")
104
+ img_btn = gr.Button("Extraire & RΓ©sumer", variant="primary")
105
+ img_text = gr.Textbox(label="Texte extrait", lines=10)
106
+ img_summary = gr.Textbox(label="RΓ©sumΓ©", lines=5)
107
+
108
+ img_btn.click(
109
+ process_image,
110
+ inputs=img_input,
111
+ outputs=[img_text, img_summary]
112
  )
 
113
 
114
+ # ----- TAB FILE -----
115
+ with gr.Tab("πŸ“„ Fichier"):
116
+ file_input = gr.File(
117
+ label="TΓ©lΓ©verser un fichier",
118
+ file_types=[".txt", ".docx", ".pptx"]
119
  )
120
+ file_btn = gr.Button("Extraire & RΓ©sumer", variant="primary")
121
+ file_text = gr.Textbox(label="Texte extrait", lines=10)
122
+ file_summary = gr.Textbox(label="RΓ©sumΓ©", lines=5)
123
+
124
+ file_btn.click(
125
+ process_file,
126
+ inputs=file_input,
127
+ outputs=[file_text, file_summary]
128
  )
129
 
 
 
 
 
 
 
 
 
130
  if __name__ == "__main__":
131
  demo.launch()