Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,13 +8,8 @@ from bs4 import BeautifulSoup
|
|
8 |
import tempfile
|
9 |
from datetime import datetime
|
10 |
|
11 |
-
# API anahtarını
|
12 |
-
|
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):
|
@@ -31,142 +26,117 @@ def extract_text_from_pdf(pdf_path):
|
|
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 |
-
#
|
48 |
prompt = f"""
|
49 |
Aşağıdaki belge metnini analiz edip özetler misin?
|
50 |
|
51 |
Belge:
|
52 |
-
{text[:15000]}
|
53 |
|
54 |
Kısa bir özet ver (1-2 paragraf):
|
55 |
"""
|
56 |
-
|
57 |
response = model.generate_content(prompt)
|
58 |
summary = response.text
|
59 |
-
|
60 |
-
#
|
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]}
|
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
|
87 |
def to_html(text):
|
88 |
return markdown.markdown(text)
|
89 |
|
90 |
-
# Word
|
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
|
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'
|
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 |
-
#
|
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
|
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
|
161 |
-
doc = create_word_document(summary, results[1:])
|
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
|
@@ -178,11 +148,11 @@ Belgedeki önemli bulgular nelerdir?
|
|
178 |
Kaç sayfa bulunmaktadır?
|
179 |
Hangi tarihte yayınlanmıştır?"""
|
180 |
|
181 |
-
# Gradio arayüzü
|
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=[
|
@@ -194,5 +164,6 @@ demo = gr.Interface(
|
|
194 |
allow_flagging="never"
|
195 |
)
|
196 |
|
197 |
-
|
198 |
-
|
|
|
|
8 |
import tempfile
|
9 |
from datetime import datetime
|
10 |
|
11 |
+
# Hugging Face secret key ile API anahtarını doğrudan konfigüre et
|
12 |
+
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
# PDF'den metin çıkarma
|
15 |
def extract_text_from_pdf(pdf_path):
|
|
|
26 |
# AI modelini kullanarak analiz yap
|
27 |
def analyze_pdf_content(text, questions):
|
28 |
try:
|
|
|
29 |
generation_config = {
|
30 |
"temperature": 0.2,
|
31 |
"top_p": 0.95,
|
32 |
"top_k": 64,
|
33 |
"max_output_tokens": 8192,
|
34 |
}
|
35 |
+
|
36 |
model = genai.GenerativeModel(
|
37 |
model_name="gemini-1.5-flash",
|
38 |
generation_config=generation_config,
|
39 |
)
|
40 |
+
|
41 |
+
# Özetleme
|
42 |
prompt = f"""
|
43 |
Aşağıdaki belge metnini analiz edip özetler misin?
|
44 |
|
45 |
Belge:
|
46 |
+
{text[:15000]}
|
47 |
|
48 |
Kısa bir özet ver (1-2 paragraf):
|
49 |
"""
|
|
|
50 |
response = model.generate_content(prompt)
|
51 |
summary = response.text
|
52 |
+
|
53 |
+
# Soru-Cevap kısmı
|
54 |
results = [summary]
|
|
|
55 |
for question in questions:
|
56 |
if not question.strip():
|
57 |
continue
|
|
|
58 |
prompt = f"""
|
59 |
Aşağıdaki belge metnine dayanarak soruyu cevapla:
|
60 |
+
|
61 |
Belge:
|
62 |
+
{text[:15000]}
|
63 |
+
|
64 |
Soru: {question}
|
65 |
+
|
66 |
Cevap:
|
67 |
"""
|
|
|
68 |
response = model.generate_content(prompt)
|
69 |
results.append((question, response.text))
|
70 |
+
|
71 |
return summary, results
|
72 |
+
|
73 |
except Exception as e:
|
74 |
return f"Analiz hatası: {str(e)}", []
|
75 |
|
76 |
+
# Markdown'ı HTML'e çevir
|
77 |
def to_html(text):
|
78 |
return markdown.markdown(text)
|
79 |
|
80 |
+
# Word raporu oluştur
|
81 |
def create_word_document(summary, results):
|
82 |
doc = Document()
|
|
|
|
|
83 |
doc.add_heading('PDF Belge Analiz Raporu', 0)
|
|
|
|
|
84 |
doc.add_paragraph(f'Oluşturulma Tarihi: {datetime.now().strftime("%d.%m.%Y %H:%M")}')
|
|
|
|
|
85 |
doc.add_heading('Belge Özeti', 1)
|
86 |
doc.add_paragraph(summary)
|
|
|
|
|
87 |
doc.add_heading('Soru ve Cevaplar', 1)
|
88 |
+
|
89 |
for i, (question, answer) in enumerate(results, 1):
|
90 |
doc.add_heading(f'Soru {i}: {question}', 2)
|
91 |
doc.add_paragraph(answer)
|
92 |
+
|
93 |
return doc
|
94 |
|
95 |
+
# Ana işlem fonksiyonu
|
96 |
def process_pdf(pdf_file, user_questions):
|
97 |
if not pdf_file:
|
98 |
return "Lütfen bir PDF dosyası yükleyin.", None
|
99 |
+
|
|
|
|
|
|
|
|
|
100 |
try:
|
101 |
+
# PDF'ten metin çıkar
|
102 |
text = extract_text_from_pdf(pdf_file)
|
|
|
103 |
if text.startswith("PDF okuma hatası"):
|
104 |
return text, None
|
105 |
+
|
106 |
# Soruları ayır
|
107 |
questions = [q.strip() for q in user_questions.split('\n') if q.strip()]
|
108 |
+
|
109 |
+
# AI ile analiz et
|
110 |
summary, results = analyze_pdf_content(text, questions)
|
|
|
111 |
if isinstance(summary, str) and summary.startswith("Analiz hatası"):
|
112 |
return summary, None
|
113 |
+
|
114 |
+
# HTML rapor oluştur
|
115 |
html_output = f"""
|
116 |
<div style="font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px;">
|
117 |
<h1>PDF Belge Analiz Raporu</h1>
|
118 |
<p><em>Oluşturulma tarihi: {datetime.now().strftime('%d.%m.%Y %H:%M')}</em></p>
|
|
|
119 |
<h2>Belge Özeti</h2>
|
120 |
<div>{to_html(summary)}</div>
|
|
|
121 |
<h2>Soru ve Cevaplar</h2>
|
122 |
"""
|
123 |
+
for i, (question, answer) in enumerate(results[1:], 1):
|
|
|
124 |
html_output += f"""
|
125 |
<div style="margin-bottom: 20px; padding: 10px; border-left: 3px solid #ccc;">
|
126 |
<h3>Soru {i}: {question}</h3>
|
127 |
<div>{to_html(answer)}</div>
|
128 |
</div>
|
129 |
"""
|
|
|
130 |
html_output += "</div>"
|
131 |
+
|
132 |
+
# Word belgesi kaydet
|
133 |
+
doc = create_word_document(summary, results[1:])
|
|
|
|
|
134 |
temp_dir = tempfile.gettempdir()
|
135 |
doc_path = os.path.join(temp_dir, f"PDF_Rapor_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx")
|
136 |
doc.save(doc_path)
|
137 |
+
|
138 |
return html_output, doc_path
|
139 |
+
|
140 |
except Exception as e:
|
141 |
error_message = f"<div style='color: red; font-weight: bold;'>İşlem sırasında bir hata oluştu: {str(e)}</div>"
|
142 |
return error_message, None
|
|
|
148 |
Kaç sayfa bulunmaktadır?
|
149 |
Hangi tarihte yayınlanmıştır?"""
|
150 |
|
151 |
+
# Gradio arayüzü
|
152 |
demo = gr.Interface(
|
153 |
fn=process_pdf,
|
154 |
inputs=[
|
155 |
+
gr.File(label="PDF Dosyası Yükleyin", file_types=[".pdf"]),
|
156 |
gr.Textbox(label="Sorularınız (Her satıra bir soru yazın)", value=default_questions, lines=10)
|
157 |
],
|
158 |
outputs=[
|
|
|
164 |
allow_flagging="never"
|
165 |
)
|
166 |
|
167 |
+
# Uygulamayı başlat
|
168 |
+
if __name__ == "__main__":
|
169 |
+
demo.launch()
|