Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,11 @@ import gradio as gr
|
|
2 |
import easyocr
|
3 |
import numpy as np
|
4 |
from transformers import pipeline
|
|
|
|
|
|
|
5 |
|
|
|
6 |
class OCRProcessor:
|
7 |
def __init__(self):
|
8 |
self.reader = easyocr.Reader(['fa'])
|
@@ -14,6 +18,38 @@ class OCRProcessor:
|
|
14 |
except Exception as e:
|
15 |
return f"خطا در پردازش OCR: {str(e)}"
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
class MultilingualQAModel:
|
18 |
def __init__(self):
|
19 |
self.qa_pipeline = pipeline(
|
@@ -34,20 +70,37 @@ class MultilingualQAModel:
|
|
34 |
except Exception as e:
|
35 |
return f"خطا در مدل پرسش و پاسخ: {str(e)}"
|
36 |
|
|
|
37 |
ocr_processor = OCRProcessor()
|
38 |
-
|
|
|
39 |
|
40 |
-
def
|
|
|
41 |
context = ocr_processor.extract_text(image)
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
-
with gr.Blocks(title="
|
46 |
gr.Markdown("""
|
47 |
-
#
|
48 |
-
|
49 |
-
|
50 |
-
3. دکمه «پاسخ» را بزنید.
|
51 |
""")
|
52 |
with gr.Row():
|
53 |
with gr.Column():
|
@@ -56,10 +109,10 @@ with gr.Blocks(title="استخراج متن و پاسخ به سوال از تص
|
|
56 |
process_btn = gr.Button("پاسخ")
|
57 |
with gr.Column():
|
58 |
context_output = gr.Textbox(label="متن استخراج شده", lines=10, max_lines=None, interactive=False)
|
59 |
-
answer_output = gr.Textbox(label="
|
60 |
|
61 |
process_btn.click(
|
62 |
-
fn=
|
63 |
inputs=[img_input, question_input],
|
64 |
outputs=[context_output, answer_output]
|
65 |
)
|
|
|
2 |
import easyocr
|
3 |
import numpy as np
|
4 |
from transformers import pipeline
|
5 |
+
from sentence_transformers import SentenceTransformer
|
6 |
+
import faiss
|
7 |
+
import torch
|
8 |
|
9 |
+
# 1. OCR Processor
|
10 |
class OCRProcessor:
|
11 |
def __init__(self):
|
12 |
self.reader = easyocr.Reader(['fa'])
|
|
|
18 |
except Exception as e:
|
19 |
return f"خطا در پردازش OCR: {str(e)}"
|
20 |
|
21 |
+
# 2. Text Chunker
|
22 |
+
def text_chunker(text, chunk_size=250, overlap=50):
|
23 |
+
words = text.split()
|
24 |
+
chunks = []
|
25 |
+
i = 0
|
26 |
+
while i < len(words):
|
27 |
+
chunk = " ".join(words[i:i+chunk_size])
|
28 |
+
chunks.append(chunk)
|
29 |
+
i += chunk_size - overlap
|
30 |
+
return chunks
|
31 |
+
|
32 |
+
# 3. Embedding Agent
|
33 |
+
class EmbeddingAgent:
|
34 |
+
def __init__(self):
|
35 |
+
self.model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
|
36 |
+
|
37 |
+
def embed(self, texts):
|
38 |
+
return self.model.encode(texts)
|
39 |
+
|
40 |
+
# 4. Retriever Agent (with FAISS)
|
41 |
+
class RetrieverAgent:
|
42 |
+
def __init__(self, embeddings, texts):
|
43 |
+
self.texts = texts
|
44 |
+
d = embeddings.shape[1]
|
45 |
+
self.index = faiss.IndexFlatL2(d)
|
46 |
+
self.index.add(embeddings)
|
47 |
+
|
48 |
+
def retrieve(self, query_embedding, top_k=1):
|
49 |
+
D, I = self.index.search(query_embedding, top_k)
|
50 |
+
return [self.texts[idx] for idx in I[0]]
|
51 |
+
|
52 |
+
# 5. QA Agent (using multilingual QA model)
|
53 |
class MultilingualQAModel:
|
54 |
def __init__(self):
|
55 |
self.qa_pipeline = pipeline(
|
|
|
70 |
except Exception as e:
|
71 |
return f"خطا در مدل پرسش و پاسخ: {str(e)}"
|
72 |
|
73 |
+
# Full DocQA Pipeline
|
74 |
ocr_processor = OCRProcessor()
|
75 |
+
embedder_agent = EmbeddingAgent()
|
76 |
+
qa_agent = MultilingualQAModel()
|
77 |
|
78 |
+
def docqa_pipeline(image, question):
|
79 |
+
# 1. OCR
|
80 |
context = ocr_processor.extract_text(image)
|
81 |
+
if context.startswith("خطا"):
|
82 |
+
return context, "پاسخی وجود ندارد"
|
83 |
+
|
84 |
+
# 2. Chunking
|
85 |
+
chunks = text_chunker(context)
|
86 |
+
|
87 |
+
# 3. Embedding (chunks + question)
|
88 |
+
chunk_embeddings = embedder_agent.embed(chunks)
|
89 |
+
question_embedding = embedder_agent.embed([question])
|
90 |
+
|
91 |
+
# 4. Retriever: پیدا کردن مرتبطترین بخش
|
92 |
+
retriever = RetrieverAgent(chunk_embeddings, chunks)
|
93 |
+
relevant_chunk = retriever.retrieve(question_embedding, top_k=1)[0]
|
94 |
+
|
95 |
+
# 5. QA: پاسخ به سوال بر اساس بخش بازیابیشده
|
96 |
+
answer = qa_agent.answer_question(relevant_chunk, question)
|
97 |
+
return context, f"متن مرتبط:\n{relevant_chunk}\n\nپاسخ مدل:\n{answer}"
|
98 |
|
99 |
+
with gr.Blocks(title="DocQA Agent: پرسش و پاسخ هوشمند از سند فارسی استخراجشده از تصویر") as app:
|
100 |
gr.Markdown("""
|
101 |
+
# DocQA Agent
|
102 |
+
<br>
|
103 |
+
یک سامانه چندعاملی برای پرسش و پاسخ از اسناد فارسی (OCR + جستجو + پاسخ هوشمند)
|
|
|
104 |
""")
|
105 |
with gr.Row():
|
106 |
with gr.Column():
|
|
|
109 |
process_btn = gr.Button("پاسخ")
|
110 |
with gr.Column():
|
111 |
context_output = gr.Textbox(label="متن استخراج شده", lines=10, max_lines=None, interactive=False)
|
112 |
+
answer_output = gr.Textbox(label="جواب مدل (بخش مرتبط و پاسخ)", lines=10, max_lines=None, interactive=False)
|
113 |
|
114 |
process_btn.click(
|
115 |
+
fn=docqa_pipeline,
|
116 |
inputs=[img_input, question_input],
|
117 |
outputs=[context_output, answer_output]
|
118 |
)
|