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