Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,23 +5,31 @@ from docx import Document
|
|
5 |
from bs4 import BeautifulSoup
|
6 |
import shutil
|
7 |
import os
|
8 |
-
import PyPDF2
|
|
|
|
|
9 |
|
10 |
-
#
|
11 |
def setup_api_key():
|
12 |
google_api_key = os.getenv("GOOGLE_API_KEY")
|
|
|
|
|
13 |
genai.configure(api_key=google_api_key)
|
14 |
|
|
|
15 |
def upload_file(file_path):
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
|
|
20 |
|
|
|
21 |
def to_markdown(text):
|
22 |
text = text.replace('•', ' *')
|
23 |
return markdown.markdown(text)
|
24 |
|
|
|
25 |
def build_model(text_file):
|
26 |
generation_config = {
|
27 |
"temperature": 0.2,
|
@@ -34,118 +42,203 @@ def build_model(text_file):
|
|
34 |
model = genai.GenerativeModel(
|
35 |
model_name="gemini-1.5-flash",
|
36 |
generation_config=generation_config,
|
37 |
-
system_instruction="""
|
38 |
-
|
|
|
39 |
)
|
40 |
|
41 |
chat_session = model.start_chat(history=[])
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
-
return chat_session
|
45 |
-
|
46 |
def chat(chat_session, prompt):
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
answer = chat(chat_session, question)
|
56 |
-
report_text += f"
|
|
|
57 |
return report_text
|
58 |
|
|
|
59 |
def convert_markdown_to_html(report_text):
|
60 |
-
html_text = markdown.markdown(report_text)
|
61 |
-
return
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
63 |
def add_html_to_word(html_text, doc):
|
64 |
soup = BeautifulSoup(html_text, 'html.parser')
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
doc.add_heading(element.get_text(), level=
|
70 |
-
elif element.name == 'h3':
|
71 |
-
doc.add_heading(element.get_text(), level=3)
|
72 |
-
elif element.name == 'h4':
|
73 |
-
doc.add_heading(element.get_text(), level=4)
|
74 |
-
elif element.name == 'h5':
|
75 |
-
doc.add_heading(element.get_text(), level=5)
|
76 |
-
elif element.name == 'h6':
|
77 |
-
doc.add_heading(element.get_text(), level=6)
|
78 |
elif element.name == 'p':
|
79 |
-
|
|
|
80 |
elif element.name == 'ul':
|
81 |
-
for li in element.find_all('li'):
|
82 |
doc.add_paragraph(li.get_text(), style='List Bullet')
|
83 |
elif element.name == 'ol':
|
84 |
-
for li in element.find_all('li'):
|
85 |
doc.add_paragraph(li.get_text(), style='List Number')
|
86 |
-
elif element.name:
|
87 |
-
doc.add_paragraph(element.get_text()) # For any other tags
|
88 |
|
|
|
89 |
def extract_text_from_pdf(pdf_path):
|
90 |
-
"""PDF dosyasından metin çıkarmak için PyPDF2 kullanır"""
|
91 |
text = ""
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
102 |
|
103 |
-
|
104 |
-
text = extract_text_from_pdf(saved_file_path)
|
105 |
|
106 |
-
#
|
107 |
-
|
108 |
-
|
|
|
109 |
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
|
149 |
-
|
150 |
-
|
151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
5 |
from bs4 import BeautifulSoup
|
6 |
import shutil
|
7 |
import os
|
8 |
+
import PyPDF2
|
9 |
+
import tempfile
|
10 |
+
from datetime import datetime
|
11 |
|
12 |
+
# API anahtarı yapılandırması
|
13 |
def setup_api_key():
|
14 |
google_api_key = os.getenv("GOOGLE_API_KEY")
|
15 |
+
if not google_api_key:
|
16 |
+
raise ValueError("GOOGLE_API_KEY çevre değişkeni ayarlanmamış.")
|
17 |
genai.configure(api_key=google_api_key)
|
18 |
|
19 |
+
# Dosya yükleme fonksiyonu
|
20 |
def upload_file(file_path):
|
21 |
+
try:
|
22 |
+
text_file = genai.upload_file(path=file_path)
|
23 |
+
return text_file
|
24 |
+
except Exception as e:
|
25 |
+
raise Exception(f"Dosya yükleme hatası: {str(e)}")
|
26 |
|
27 |
+
# Markdown formatına dönüştürme
|
28 |
def to_markdown(text):
|
29 |
text = text.replace('•', ' *')
|
30 |
return markdown.markdown(text)
|
31 |
|
32 |
+
# AI modelini oluşturma
|
33 |
def build_model(text_file):
|
34 |
generation_config = {
|
35 |
"temperature": 0.2,
|
|
|
42 |
model = genai.GenerativeModel(
|
43 |
model_name="gemini-1.5-flash",
|
44 |
generation_config=generation_config,
|
45 |
+
system_instruction="""PDF belgesinden yüklenen bilgilere dayanarak soruları cevapla.
|
46 |
+
Belge içinde ilgili bilgi yoksa 'Bu konuda belgede bilgi bulamadım.' diye yanıtla.
|
47 |
+
Cevaplarında mümkün olduğunca belgedeki bilgileri referans ver ve doğru bilgi sağla.""",
|
48 |
)
|
49 |
|
50 |
chat_session = model.start_chat(history=[])
|
51 |
+
|
52 |
+
# Belgeyi özetleyerek başla
|
53 |
+
response = chat_session.send_message(["Bu belgeyi kısaca özetle", text_file])
|
54 |
+
return chat_session, response.text
|
55 |
|
56 |
+
# Sohbet fonksiyonu
|
|
|
|
|
57 |
def chat(chat_session, prompt):
|
58 |
+
try:
|
59 |
+
response = chat_session.send_message(prompt)
|
60 |
+
return response.text
|
61 |
+
except Exception as e:
|
62 |
+
return f"Yanıt alınamadı: {str(e)}"
|
63 |
+
|
64 |
+
# Rapor oluşturma
|
65 |
+
def generate_report(chat_session, questions, summary):
|
66 |
+
report_text = "# PDF Belge Analiz Raporu\n\n"
|
67 |
+
report_text += f"*Oluşturulma tarihi: {datetime.now().strftime('%d.%m.%Y %H:%M')}*\n\n"
|
68 |
+
report_text += f"## Belge Özeti\n\n{summary}\n\n"
|
69 |
+
report_text += f"## Soru ve Cevaplar\n\n"
|
70 |
+
|
71 |
+
for i, question in enumerate(questions, 1):
|
72 |
+
if not question.strip():
|
73 |
+
continue
|
74 |
+
report_text += f"### Soru {i}: {question}\n\n"
|
75 |
answer = chat(chat_session, question)
|
76 |
+
report_text += f"{answer}\n\n"
|
77 |
+
|
78 |
return report_text
|
79 |
|
80 |
+
# Markdown'ı HTML'e dönüştürme
|
81 |
def convert_markdown_to_html(report_text):
|
82 |
+
html_text = markdown.markdown(report_text, extensions=['tables'])
|
83 |
+
return f"""
|
84 |
+
<div style="font-family: Arial, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px;">
|
85 |
+
{html_text}
|
86 |
+
</div>
|
87 |
+
"""
|
88 |
+
|
89 |
+
# HTML'i Word belgesine ekleme
|
90 |
def add_html_to_word(html_text, doc):
|
91 |
soup = BeautifulSoup(html_text, 'html.parser')
|
92 |
+
|
93 |
+
for element in soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'ul', 'ol', 'li']):
|
94 |
+
if element.name.startswith('h') and element.name[1:].isdigit():
|
95 |
+
level = int(element.name[1])
|
96 |
+
doc.add_heading(element.get_text(), level=level)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
elif element.name == 'p':
|
98 |
+
if element.get_text().strip():
|
99 |
+
doc.add_paragraph(element.get_text())
|
100 |
elif element.name == 'ul':
|
101 |
+
for li in element.find_all('li', recursive=False):
|
102 |
doc.add_paragraph(li.get_text(), style='List Bullet')
|
103 |
elif element.name == 'ol':
|
104 |
+
for li in element.find_all('li', recursive=False):
|
105 |
doc.add_paragraph(li.get_text(), style='List Number')
|
|
|
|
|
106 |
|
107 |
+
# PDF'den metin çıkarma
|
108 |
def extract_text_from_pdf(pdf_path):
|
|
|
109 |
text = ""
|
110 |
+
try:
|
111 |
+
with open(pdf_path, 'rb') as file:
|
112 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
113 |
+
for page_num in range(len(pdf_reader.pages)):
|
114 |
+
text += pdf_reader.pages[page_num].extract_text() + "\n"
|
115 |
+
return text
|
116 |
+
except Exception as e:
|
117 |
+
raise Exception(f"PDF okuma hatası: {str(e)}")
|
118 |
+
|
119 |
+
# Ana işlem fonksiyonu
|
120 |
+
def process_pdf(pdf_file, user_questions, progress=gr.Progress()):
|
121 |
+
if not pdf_file:
|
122 |
+
return "Lütfen bir PDF dosyası yükleyin.", None
|
123 |
|
124 |
+
progress(0, desc="PDF yükleniyor...")
|
|
|
125 |
|
126 |
+
# Geçici dosya ve klasör yönetimi
|
127 |
+
temp_dir = tempfile.mkdtemp()
|
128 |
+
file_name = os.path.basename(pdf_file)
|
129 |
+
pdf_path = os.path.join(temp_dir, file_name)
|
130 |
|
131 |
+
try:
|
132 |
+
# PDF dosyasını geçici konuma kopyala
|
133 |
+
shutil.copyfile(pdf_file, pdf_path)
|
134 |
+
|
135 |
+
progress(20, desc="PDF'den metin çıkarılıyor...")
|
136 |
+
text = extract_text_from_pdf(pdf_path)
|
137 |
+
|
138 |
+
# Çıkarılan metni bir dosyaya yaz
|
139 |
+
text_file_path = os.path.join(temp_dir, "extracted_text.txt")
|
140 |
+
with open(text_file_path, "w", encoding="utf-8") as f:
|
141 |
+
f.write(text)
|
142 |
+
|
143 |
+
progress(40, desc="Metin dosyası yükleniyor...")
|
144 |
+
text_file = upload_file(text_file_path)
|
145 |
+
|
146 |
+
progress(60, desc="AI modeli hazırlanıyor...")
|
147 |
+
chat_session, summary = build_model(text_file)
|
148 |
+
|
149 |
+
progress(70, desc="Sorular işleniyor...")
|
150 |
+
# Soruları ayırma
|
151 |
+
questions = [q.strip() for q in user_questions.split('\n') if q.strip()]
|
152 |
+
|
153 |
+
progress(80, desc="Rapor oluşturuluyor...")
|
154 |
+
report_text = generate_report(chat_session, questions, summary)
|
155 |
+
|
156 |
+
progress(90, desc="Sonuçlar formatlanıyor...")
|
157 |
+
html_output = convert_markdown_to_html(report_text)
|
158 |
+
|
159 |
+
# Word belgesi oluştur
|
160 |
+
doc = Document()
|
161 |
+
add_html_to_word(html_output, doc)
|
162 |
+
|
163 |
+
doc_name = f"PDF_Rapor_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
|
164 |
+
doc_path = os.path.join(temp_dir, doc_name)
|
165 |
+
doc.save(doc_path)
|
166 |
+
|
167 |
+
progress(100, desc="Tamamlandı!")
|
168 |
+
return html_output, doc_path
|
169 |
+
|
170 |
+
except Exception as e:
|
171 |
+
error_message = f"<div style='color: red; font-weight: bold;'>Hata oluştu: {str(e)}</div>"
|
172 |
+
return error_message, None
|
173 |
+
finally:
|
174 |
+
# Geçici dosyaları silme işlemi (opsiyonel)
|
175 |
+
pass
|
176 |
+
|
177 |
+
# Varsayılan sorular
|
178 |
+
default_questions = """Belgenin ana konusu nedir?
|
179 |
+
Belgenin yazarları kimlerdir?
|
180 |
+
Belgedeki önemli bulgular nelerdir?
|
181 |
+
Kaç sayfa ve bölüm vardır?
|
182 |
+
Hangi tarihte yayınlanmıştır?"""
|
183 |
+
|
184 |
+
# Gradio arayüzü
|
185 |
+
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
186 |
+
gr.Markdown("""
|
187 |
+
# 📄 PDF Soru-Cevap Asistanı
|
188 |
+
|
189 |
+
Bu uygulama, yüklediğiniz PDF belgesi üzerinde sorular sormanıza ve detaylı bir rapor almanıza olanak tanır.
|
190 |
+
""")
|
191 |
+
|
192 |
+
with gr.Row():
|
193 |
+
with gr.Column(scale=1):
|
194 |
+
pdf_input = gr.File(
|
195 |
+
label="PDF Dosyası Yükleyin",
|
196 |
+
file_types=[".pdf"],
|
197 |
+
type="filepath"
|
198 |
+
)
|
199 |
+
|
200 |
+
questions_input = gr.TextArea(
|
201 |
+
label="Sorularınız",
|
202 |
+
placeholder="Her satıra bir soru yazın...",
|
203 |
+
value=default_questions,
|
204 |
+
lines=10
|
205 |
+
)
|
206 |
+
|
207 |
+
submit_btn = gr.Button("📝 Rapor Oluştur", variant="primary")
|
208 |
+
|
209 |
+
with gr.Column(scale=2):
|
210 |
+
with gr.Tabs():
|
211 |
+
with gr.Tab("HTML Görünüm"):
|
212 |
+
html_output = gr.HTML(label="Rapor Sonucu")
|
213 |
+
with gr.Tab("İndirilebilir Dosya"):
|
214 |
+
file_output = gr.File(label="DOCX Rapor")
|
215 |
+
|
216 |
+
with gr.Accordion("Nasıl Kullanılır?", open=False):
|
217 |
+
gr.Markdown("""
|
218 |
+
### Kullanım Adımları:
|
219 |
+
1. PDF dosyanızı yükleyin
|
220 |
+
2. Belge hakkında cevaplarını almak istediğiniz soruları yazın
|
221 |
+
3. "Rapor Oluştur" düğmesine basın
|
222 |
+
4. Oluşturulan raporu HTML olarak görüntüleyin veya DOCX dosyası olarak indirin
|
223 |
+
|
224 |
+
### İpuçları:
|
225 |
+
- Her satıra bir soru yazın
|
226 |
+
- Belgenin içeriğiyle ilgili net sorular sorun
|
227 |
+
- Büyük PDF'ler için işlem süresi uzayabilir
|
228 |
+
""")
|
229 |
+
|
230 |
+
submit_btn.click(
|
231 |
+
fn=process_pdf,
|
232 |
+
inputs=[pdf_input, questions_input],
|
233 |
+
outputs=[html_output, file_output],
|
234 |
+
show_progress=True
|
235 |
+
)
|
236 |
|
237 |
+
# API anahtarını ayarla ve uygulamayı başlat
|
238 |
+
if __name__ == "__main__":
|
239 |
+
try:
|
240 |
+
setup_api_key()
|
241 |
+
iface.launch(share=True)
|
242 |
+
except ValueError as e:
|
243 |
+
print(f"Hata: {str(e)}")
|
244 |
+
print("Lütfen GOOGLE_API_KEY çevre değişkenini ayarlayın.")
|