NOBODY204 commited on
Commit
8f60d7b
·
verified ·
1 Parent(s): 85bd81a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -39
app.py CHANGED
@@ -5,15 +5,16 @@ import re
5
  import easyocr
6
  import pdf2image
7
  import numpy as np
8
- import os
9
- from transformers import MBartForConditionalGeneration, MBart50TokenizerFast
 
10
 
11
  # -----------------------------
12
- # 1️⃣ OCR en arabe
13
  # -----------------------------
14
- reader = easyocr.Reader(['ar']) # OCR pour l'arabe
15
 
16
- def ocr_pdf_arabic(file_path):
17
  pages = pdf2image.convert_from_path(file_path, dpi=300)
18
  text = ""
19
  for page in pages:
@@ -22,51 +23,40 @@ def ocr_pdf_arabic(file_path):
22
  return text
23
 
24
  # -----------------------------
25
- # 2️⃣ Logique de rangement (11 boîtes par étage)
26
  # -----------------------------
27
  def calculer_emplacement(n):
28
  try:
29
  if n is None or n < 1:
30
  return "### ⚠️ En attente d'un numéro de boîte..."
31
-
32
  n = int(n)
33
  etage = ((n - 1) // 11) + 1
34
  rayon = "A" if n <= 11 else "B"
35
  case = ((n - 1) % 11) + 1
36
-
37
  return f"""
38
- # 📍 EMPLACEMENT TROUVÉ
39
- ---
40
- ## 📦 BOÎTE N° : {n}
41
- ## 🏢 RAYON : **{rayon}**
42
- ## 📏 ÉTAGE : **{etage}**
43
- ## 🔢 CASE (Position) : **{case} / 11**
44
- ---
45
- *Instructions : Allez au Rayon {rayon}, montez à l'étage {etage} et prenez la {case}ème boîte.*
46
- """
47
  except:
48
  return "❌ Erreur de saisie."
49
 
50
  # -----------------------------
51
- # 3️⃣ Modèle résumé fidèle arabe
52
  # -----------------------------
53
- print("Chargement du modèle mBART multilingue pour résumé arabe...")
54
- model_name = "facebook/mbart-large-50-many-to-many-mmt"
55
- tokenizer = MBart50TokenizerFast.from_pretrained(model_name)
56
- model = MBartForConditionalGeneration.from_pretrained(model_name)
57
-
58
- def summarize_arabic(text, longueur):
59
- # Tokenizer et génération
60
- tokenizer.src_lang = "ar_AR"
61
- inputs = tokenizer(text, return_tensors="pt", max_length=1024, truncation=True)
62
- max_len = 180 if longueur == "Détaillé" else 80
63
- min_len = 50 if longueur == "Détaillé" else 20
64
- summary_ids = model.generate(inputs["input_ids"], max_length=max_len, min_length=min_len, do_sample=False)
65
- summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
66
- return summary
67
 
68
  # -----------------------------
69
- # 4️⃣ Classe d'analyse PDF
70
  # -----------------------------
71
  class ArchivAppV15:
72
  def analyser_pdf(self, file, longueur):
@@ -80,15 +70,16 @@ class ArchivAppV15:
80
  if content:
81
  text += content + " "
82
 
83
- # Si texte trop court → OCR arabe
84
  if len(text.strip()) < 50:
85
- text = ocr_pdf_arabic(file.name)
86
 
87
  clean_text = re.sub(r"\s+", " ", text).strip()
88
  if len(clean_text) < 50:
89
  return "❌ Document trop court après OCR", ""
90
 
91
- summary = summarize_arabic(clean_text, longueur)
 
92
 
93
  return "✅ Synthèse réussie", summary
94
  except Exception as e:
@@ -100,7 +91,7 @@ app = ArchivAppV15()
100
  # 5️⃣ Interface Gradio
101
  # -----------------------------
102
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
103
- gr.Markdown("# 📁 ArchivChat V15 - Gestion & Synthèse Arabe")
104
 
105
  with gr.Tab("📍 Localisation"):
106
  gr.Markdown("### Calcul automatique : 11 boîtes par étage")
@@ -109,9 +100,9 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
109
  output_loc = gr.Markdown("### L'emplacement détaillé s'affichera ici")
110
  input_num.change(calculer_emplacement, inputs=input_num, outputs=output_loc)
111
 
112
- with gr.Tab("📄 Résumé Arabe"):
113
  with gr.Row():
114
- file_in = gr.File(label="Déposer le PDF d'archive (arabe)", file_types=[".pdf"])
115
  longueur_opt = gr.Radio(["Court", "Détaillé"], label="Style de résumé", value="Court")
116
  btn_res = gr.Button("Lancer l'analyse ✨", variant="primary")
117
  with gr.Row():
 
5
  import easyocr
6
  import pdf2image
7
  import numpy as np
8
+ from sumy.parsers.plaintext import PlaintextParser
9
+ from sumy.nlp.tokenizers import Tokenizer
10
+ from sumy.summarizers.lex_rank import LexRankSummarizer
11
 
12
  # -----------------------------
13
+ # 1️⃣ OCR arabe + français
14
  # -----------------------------
15
+ reader = easyocr.Reader(['ar', 'fr'])
16
 
17
+ def ocr_pdf_multilang(file_path):
18
  pages = pdf2image.convert_from_path(file_path, dpi=300)
19
  text = ""
20
  for page in pages:
 
23
  return text
24
 
25
  # -----------------------------
26
+ # 2️⃣ Calcul emplacement (11 boîtes / étage)
27
  # -----------------------------
28
  def calculer_emplacement(n):
29
  try:
30
  if n is None or n < 1:
31
  return "### ⚠️ En attente d'un numéro de boîte..."
 
32
  n = int(n)
33
  etage = ((n - 1) // 11) + 1
34
  rayon = "A" if n <= 11 else "B"
35
  case = ((n - 1) % 11) + 1
 
36
  return f"""
37
+ # 📍 EMPLACEMENT TROUVÉ
38
+ ---
39
+ ## 📦 BOÎTE N° : {n}
40
+ ## 🏢 RAYON : **{rayon}**
41
+ ## 📏 ÉTAGE : **{etage}**
42
+ ## 🔢 CASE (Position) : **{case} / 11**
43
+ ---
44
+ *Instructions : Allez au Rayon {rayon}, montez à l'étage {etage} et prenez la {case}ème boîte.*
45
+ """
46
  except:
47
  return "❌ Erreur de saisie."
48
 
49
  # -----------------------------
50
+ # 3️⃣ Résumé extractif fiable hors-ligne
51
  # -----------------------------
52
+ def summarize_offline(text, n_sentences=5):
53
+ parser = PlaintextParser.from_string(text, Tokenizer("arabic"))
54
+ summarizer = LexRankSummarizer()
55
+ summary = summarizer(parser.document, sentences_count=n_sentences)
56
+ return " ".join([str(sentence) for sentence in summary])
 
 
 
 
 
 
 
 
 
57
 
58
  # -----------------------------
59
+ # 4️⃣ Classe analyse PDF
60
  # -----------------------------
61
  class ArchivAppV15:
62
  def analyser_pdf(self, file, longueur):
 
70
  if content:
71
  text += content + " "
72
 
73
+ # Si texte trop court → OCR
74
  if len(text.strip()) < 50:
75
+ text = ocr_pdf_multilang(file.name)
76
 
77
  clean_text = re.sub(r"\s+", " ", text).strip()
78
  if len(clean_text) < 50:
79
  return "❌ Document trop court après OCR", ""
80
 
81
+ n_sentences = 10 if longueur == "Détaillé" else 5
82
+ summary = summarize_offline(clean_text, n_sentences=n_sentences)
83
 
84
  return "✅ Synthèse réussie", summary
85
  except Exception as e:
 
91
  # 5️⃣ Interface Gradio
92
  # -----------------------------
93
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
94
+ gr.Markdown("# 📁 ArchivChat V15 - Gestion & Synthèse Arabe + Français")
95
 
96
  with gr.Tab("📍 Localisation"):
97
  gr.Markdown("### Calcul automatique : 11 boîtes par étage")
 
100
  output_loc = gr.Markdown("### L'emplacement détaillé s'affichera ici")
101
  input_num.change(calculer_emplacement, inputs=input_num, outputs=output_loc)
102
 
103
+ with gr.Tab("📄 Résumé Multilingue"):
104
  with gr.Row():
105
+ file_in = gr.File(label="Déposer le PDF d'archive (arabe ou français)", file_types=[".pdf"])
106
  longueur_opt = gr.Radio(["Court", "Détaillé"], label="Style de résumé", value="Court")
107
  btn_res = gr.Button("Lancer l'analyse ✨", variant="primary")
108
  with gr.Row():