Spaces:
Sleeping
Sleeping
hayabusa
fix: remove PDF text truncation and add StrOutputParser to properly parse Gemini responses
015ecd9 | import os | |
| import sys | |
| # Mock pyaudioop/audioop for Python 3.13+ compatibility | |
| import pyaudioop_mock | |
| try: | |
| from pypdf import PdfReader | |
| import gradio as gr | |
| from langchain_core.prompts import PromptTemplate | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| from langchain_core.output_parsers import StrOutputParser | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| print("✅ Tüm kütüphaneler başarıyla yüklendi") | |
| except ImportError as e: | |
| print(f"❌ Import hatası: {e}") | |
| sys.exit(1) | |
| # API anahtarını environment variable'dan al | |
| GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") | |
| # API key durumunu kontrol et | |
| if GEMINI_API_KEY: | |
| print(f"✅ API Key yüklendi (ilk 10 karakter: {GEMINI_API_KEY[:10]}...)") | |
| else: | |
| print("❌ GEMINI_API_KEY environment variable bulunamadı!") | |
| def extract_text_from_pdf(pdf_file): | |
| """PDF'den metin çıkarır""" | |
| try: | |
| text = "" | |
| pdf_reader = PdfReader(pdf_file) | |
| for page in pdf_reader.pages: | |
| text += page.extract_text() + "\n" | |
| return text.strip() | |
| except Exception as e: | |
| return f"PDF okuma hatası: {str(e)}" | |
| def answer_question(pdf_file, question): | |
| """PDF'e soru sorar ve cevap alır""" | |
| try: | |
| # API key kontrolü - sadece .env'den al | |
| if not GEMINI_API_KEY: | |
| return "❌ GEMINI_API_KEY environment variable ayarlanmamış. Lütfen .env dosyasına ekleyin." | |
| if not pdf_file: | |
| return "❌ Lütfen bir PDF dosyası yükleyin" | |
| if not question: | |
| return "❌ Lütfen bir soru sorun" | |
| # PDF'den metin çıkar | |
| pdf_text = extract_text_from_pdf(pdf_file) | |
| if "hata" in pdf_text.lower(): | |
| return pdf_text | |
| if len(pdf_text) < 10: | |
| return "❌ PDF'den yeterli metin çıkarılamadı" | |
| # LLM setup | |
| llm = ChatGoogleGenerativeAI( | |
| api_key=GEMINI_API_KEY, | |
| model="gemini-3.1-flash-lite", | |
| temperature=0 | |
| ) | |
| # Prompt template | |
| prompt = PromptTemplate( | |
| template="""PDF içeriğine dayanarak soruyu yanıtla. | |
| PDF İçeriği: {context} | |
| Soru: {question} | |
| Yanıt:""", | |
| input_variables=["context", "question"] | |
| ) | |
| # Tüm metni kullan (Gemini'nin token limiti çok yüksektir) | |
| context = pdf_text | |
| # LCEL chain | |
| chain = prompt | llm | StrOutputParser() | |
| response = chain.invoke({"context": context, "question": question}) | |
| return f"**Soru:** {question}\n\n**Cevap:** {response}" | |
| except Exception as e: | |
| return f"❌ Hata: {str(e)}" | |
| # Gradio Blocks interface (daha stabil) | |
| css = """ | |
| .gradio-container { | |
| max-width: 1200px !important; | |
| } | |
| """ | |
| with gr.Blocks(title="🚀 PDF Soru-Cevap", css=css) as demo: | |
| gr.Markdown("# 🚀 PDF Soru-Cevap") | |
| api_status = "🔐 API anahtarı environment variable ile ayarlanmış ✅" if GEMINI_API_KEY else "❌ GEMINI_API_KEY environment variable ayarlanmamış" | |
| gr.Markdown(f""" | |
| PDF dosyanızı yükleyin ve Gemini AI ile sorularınızı sorun! | |
| {api_status} | |
| **Örnek sorular:** | |
| - Bu dökümanın ana konusu nedir? | |
| - Hangi tarihlerde yapılan çalışmalardan bahsediliyor? | |
| - Önemli noktaları özetle | |
| - Bu PDF'de hangi konular ele alınıyor? | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| pdf_input = gr.File(label="📄 PDF Dosyası", file_types=[".pdf"]) | |
| question_input = gr.Textbox( | |
| label="❓ Sorunuz", | |
| placeholder="PDF hakkında sorunuzu yazın...", | |
| lines=2 | |
| ) | |
| submit_btn = gr.Button("🚀 Soru Sor", variant="primary") | |
| with gr.Column(): | |
| output = gr.Textbox( | |
| label="🤖 Cevap", | |
| lines=15, | |
| placeholder="Cevabınız burada görünecek..." | |
| ) | |
| submit_btn.click( | |
| fn=answer_question, | |
| inputs=[pdf_input, question_input], | |
| outputs=output | |
| ) | |
| # Enter tuşu ile de gönderebilsin | |
| question_input.submit( | |
| fn=answer_question, | |
| inputs=[pdf_input, question_input], | |
| outputs=output | |
| ) | |
| if __name__ == "__main__": | |
| # Hugging Face Spaces için basit launch | |
| demo.launch() | |