yunuseduran commited on
Commit
a974597
·
verified ·
1 Parent(s): 702c6ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -191
app.py CHANGED
@@ -1,244 +1,199 @@
1
  import gradio as gr
2
  import google.generativeai as genai
 
 
3
  import markdown
4
  from docx import Document
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,
36
- "top_p": 0.95,
37
- "top_k": 64,
38
- "max_output_tokens": 8192,
39
- "response_mime_type": "text/plain",
40
- }
41
-
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.")
 
1
  import gradio as gr
2
  import google.generativeai as genai
3
+ import os
4
+ import PyPDF2
5
  import markdown
6
  from docx import Document
7
  from bs4 import BeautifulSoup
 
 
 
8
  import tempfile
9
  from datetime import datetime
10
 
11
+ # API anahtarını ayarla
12
  def setup_api_key():
13
  google_api_key = os.getenv("GOOGLE_API_KEY")
14
  if not google_api_key:
15
+ return False
16
  genai.configure(api_key=google_api_key)
17
+ return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  # PDF'den metin çıkarma
20
  def extract_text_from_pdf(pdf_path):
 
21
  try:
22
+ text = ""
23
  with open(pdf_path, 'rb') as file:
24
  pdf_reader = PyPDF2.PdfReader(file)
25
  for page_num in range(len(pdf_reader.pages)):
26
  text += pdf_reader.pages[page_num].extract_text() + "\n"
27
  return text
28
  except Exception as e:
29
+ return f"PDF okuma hatası: {str(e)}"
30
+
31
+ # AI modelini kullanarak analiz yap
32
+ def analyze_pdf_content(text, questions):
33
+ try:
34
+ # Gemini modeli yapılandırma
35
+ generation_config = {
36
+ "temperature": 0.2,
37
+ "top_p": 0.95,
38
+ "top_k": 64,
39
+ "max_output_tokens": 8192,
40
+ }
41
+
42
+ model = genai.GenerativeModel(
43
+ model_name="gemini-1.5-flash",
44
+ generation_config=generation_config,
45
+ )
46
+
47
+ # İlk önce belgeyi özetle
48
+ prompt = f"""
49
+ Aşağıdaki belge metnini analiz edip özetler misin?
50
+
51
+ Belge:
52
+ {text[:15000]} # Çok uzun metinlerde kesme yapabilirsiniz
53
+
54
+ Kısa bir özet ver (1-2 paragraf):
55
+ """
56
+
57
+ response = model.generate_content(prompt)
58
+ summary = response.text
59
+
60
+ # Sonra soruları yanıtla
61
+ results = [summary]
62
+
63
+ for question in questions:
64
+ if not question.strip():
65
+ continue
66
+
67
+ prompt = f"""
68
+ Aşağıdaki belge metnine dayanarak soruyu cevapla:
69
+
70
+ Belge:
71
+ {text[:15000]} # Çok uzun metinlerde kesme yapabilirsiniz
72
+
73
+ Soru: {question}
74
+
75
+ Cevap:
76
+ """
77
+
78
+ response = model.generate_content(prompt)
79
+ results.append((question, response.text))
80
+
81
+ return summary, results
82
+
83
+ except Exception as e:
84
+ return f"Analiz hatası: {str(e)}", []
85
 
86
+ # Markdown'ı HTML'e dönüştürme
87
+ def to_html(text):
88
+ return markdown.markdown(text)
89
+
90
+ # Word belgesi oluşturma
91
+ def create_word_document(summary, results):
92
+ doc = Document()
93
+
94
+ # Başlık ekle
95
+ doc.add_heading('PDF Belge Analiz Raporu', 0)
96
+
97
+ # Tarih ekle
98
+ doc.add_paragraph(f'Oluşturulma Tarihi: {datetime.now().strftime("%d.%m.%Y %H:%M")}')
99
+
100
+ # Özet bölümü
101
+ doc.add_heading('Belge Özeti', 1)
102
+ doc.add_paragraph(summary)
103
+
104
+ # Soru ve cevaplar
105
+ doc.add_heading('Soru ve Cevaplar', 1)
106
+
107
+ for i, (question, answer) in enumerate(results, 1):
108
+ doc.add_heading(f'Soru {i}: {question}', 2)
109
+ doc.add_paragraph(answer)
110
+
111
+ return doc
112
+
113
+ # Ana işleme fonksiyonu
114
+ def process_pdf(pdf_file, user_questions):
115
  if not pdf_file:
116
  return "Lütfen bir PDF dosyası yükleyin.", None
117
 
118
+ # API anahtarını kontrol et
119
+ if not setup_api_key():
120
+ return "GOOGLE_API_KEY çevre değişkeni ayarlanmamış. Lütfen API anahtarınızı ekleyin.", None
 
 
 
121
 
122
  try:
123
+ # PDF'den metin çıkar
124
+ text = extract_text_from_pdf(pdf_file)
125
 
126
+ if text.startswith("PDF okuma hatası"):
127
+ return text, None
128
 
129
+ # Soruları ayır
130
+ questions = [q.strip() for q in user_questions.split('\n') if q.strip()]
 
 
131
 
132
+ # Metni analiz et
133
+ summary, results = analyze_pdf_content(text, questions)
134
 
135
+ if isinstance(summary, str) and summary.startswith("Analiz hatası"):
136
+ return summary, None
137
 
138
+ # HTML raporu oluştur
139
+ html_output = f"""
140
+ <div style="font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px;">
141
+ <h1>PDF Belge Analiz Raporu</h1>
142
+ <p><em>Oluşturulma tarihi: {datetime.now().strftime('%d.%m.%Y %H:%M')}</em></p>
143
+
144
+ <h2>Belge Özeti</h2>
145
+ <div>{to_html(summary)}</div>
146
+
147
+ <h2>Soru ve Cevaplar</h2>
148
+ """
149
 
150
+ for i, (question, answer) in enumerate(results[1:], 1): # İlk sonuç zaten özet
151
+ html_output += f"""
152
+ <div style="margin-bottom: 20px; padding: 10px; border-left: 3px solid #ccc;">
153
+ <h3>Soru {i}: {question}</h3>
154
+ <div>{to_html(answer)}</div>
155
+ </div>
156
+ """
157
 
158
+ html_output += "</div>"
 
159
 
160
  # Word belgesi oluştur
161
+ doc = create_word_document(summary, results[1:]) # İlk sonuç zaten özet
 
162
 
163
+ # Geçici dosya oluştur
164
+ temp_dir = tempfile.gettempdir()
165
+ doc_path = os.path.join(temp_dir, f"PDF_Rapor_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx")
166
  doc.save(doc_path)
167
 
 
168
  return html_output, doc_path
169
 
170
  except Exception as e:
171
+ error_message = f"<div style='color: red; font-weight: bold;'>İşlem sırasında bir hata oluştu: {str(e)}</div>"
172
  return error_message, None
 
 
 
173
 
174
  # Varsayılan sorular
175
  default_questions = """Belgenin ana konusu nedir?
176
  Belgenin yazarları kimlerdir?
177
  Belgedeki önemli bulgular nelerdir?
178
+ Kaç sayfa bulunmaktadır?
179
  Hangi tarihte yayınlanmıştır?"""
180
 
181
+ # Gradio arayüzü oluştur - basit Interface kullanarak
182
+ demo = gr.Interface(
183
+ fn=process_pdf,
184
+ inputs=[
185
+ gr.File(label="PDF Dosyası Yükleyin", file_types=[".pdf"]),
186
+ gr.Textbox(label="Sorularınız (Her satıra bir soru yazın)", value=default_questions, lines=10)
187
+ ],
188
+ outputs=[
189
+ gr.HTML(label="Rapor Sonucu"),
190
+ gr.File(label="Word Belgesi")
191
+ ],
192
+ title="PDF Belgelerinden Soru-Cevap Raporu Oluşturma Aracı",
193
+ description="PDF belgelerinizi yükleyin ve istediğiniz soruları sorun. AI destekli sistem belgenizi analiz edip yanıtları içeren bir rapor hazırlayacaktır.",
194
+ allow_flagging="never"
195
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
+ # Uygulamayı başlat
198
  if __name__ == "__main__":
199
+ demo.launch()