yunuseduran commited on
Commit
8ab61e6
·
verified ·
1 Parent(s): 9da60a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -98
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 # PDF işleme için subprocess yerine Python kütüphanesi kullanın
 
 
9
 
10
- # Setup your API key
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
- print(f"Uploading file...")
17
- text_file = genai.upload_file(path=file_path)
18
- print(f"Completed upload: {text_file.uri}")
19
- return text_file
 
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="""Answer the questions based on the uploaded file.
38
- If there is no related info in the file just reply 'I don't know.' """,
 
39
  )
40
 
41
  chat_session = model.start_chat(history=[])
 
 
 
 
42
 
43
- response = chat_session.send_message(["Summarize the doc in one sentence", text_file])
44
- return chat_session
45
-
46
  def chat(chat_session, prompt):
47
- response = chat_session.send_message(prompt)
48
- return response.text
49
-
50
- def generate_report(chat_session, questions):
51
- report_text = ""
52
- report_text += f"\n## QUESTIONS & ANSWERS\n"
53
- for question in questions:
54
- report_text += f"\n## {question}\n"
 
 
 
 
 
 
 
 
 
55
  answer = chat(chat_session, question)
56
- report_text += f"\n{answer}\n"
 
57
  return report_text
58
 
 
59
  def convert_markdown_to_html(report_text):
60
- html_text = markdown.markdown(report_text)
61
- return html_text
62
-
 
 
 
 
 
63
  def add_html_to_word(html_text, doc):
64
  soup = BeautifulSoup(html_text, 'html.parser')
65
- for element in soup:
66
- if element.name == 'h1':
67
- doc.add_heading(element.get_text(), level=1)
68
- elif element.name == 'h2':
69
- doc.add_heading(element.get_text(), level=2)
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
- doc.add_paragraph(element.get_text())
 
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
- with open(pdf_path, 'rb') as file:
93
- pdf_reader = PyPDF2.PdfReader(file)
94
- for page_num in range(len(pdf_reader.pages)):
95
- text += pdf_reader.pages[page_num].extract_text() + "\n"
96
- return text
97
-
98
- def process_pdf(pdf_file, user_questions):
99
- file_name = pdf_file.split('/')[-1]
100
- saved_file_path = f"/tmp/{file_name}"
101
- shutil.copyfile(pdf_file, saved_file_path)
 
 
 
102
 
103
- # PDF'den doğrudan metin çıkar
104
- text = extract_text_from_pdf(saved_file_path)
105
 
106
- # Çıkarılan metni bir dosyaya yaz
107
- with open("/tmp/text_file.txt", "w", encoding="utf-8") as f:
108
- f.write(text)
 
109
 
110
- text_file = upload_file("/tmp/text_file.txt")
111
- chat_session = build_model(text_file)
112
-
113
- questions = user_questions.strip().split('\n')
114
- report_text = generate_report(chat_session, questions)
115
-
116
- doc = Document()
117
- html_text = convert_markdown_to_html(report_text)
118
- add_html_to_word(html_text, doc)
119
-
120
- doc_name = file_name.replace(".pdf", ".docx")
121
- doc_name = "Report_" + doc_name
122
- doc.save(f"/tmp/{doc_name}")
123
-
124
- return html_text, f"/tmp/{doc_name}"
125
-
126
- questions = [
127
- "Makalenin yazarları kimlerdir?",
128
- "Hangi modeller kullanılmıştır?",
129
- "Kaç referans vardır?",
130
- "Hangi yılda yayınlanmıştır?"
131
- ]
132
-
133
- questions_str = "\n".join(questions)
134
-
135
- iface = gr.Interface(
136
- fn=process_pdf,
137
- inputs=[
138
- gr.File(label="Upload PDF", type="filepath"),
139
- gr.TextArea(label="Enter Questions", placeholder="Type your questions here, one per line.", value=questions_str)
140
- ],
141
- outputs=[
142
- gr.HTML(label="HTML Formatted Report"),
143
- gr.File(label="DOCX File Output", type="binary")
144
- ],
145
- title="Pdflerinizden kısa rapor oluşturma arac @YED",
146
- description="Sorularınızı sormak ve cevap almak için PDF'inizi yükleyin."
147
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- setup_api_key()
150
- # Hugging Face Spaces için önerilen launch konfigürasyonu
151
- iface.launch(share=True)
 
 
 
 
 
 
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.")