Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -20,6 +20,7 @@ LLM_MODEL_NAME = "mrm8488/bert2bert_shared-turkish-summarization"
|
|
| 20 |
MAX_NEW_TOKENS = 256
|
| 21 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
|
|
|
|
| 23 |
# --- 1. PDF'ten Vektör Veritabanı Oluştur ---
|
| 24 |
def create_vector_db_from_pdf(pdf_path):
|
| 25 |
print(f"📄 PDF okunuyor: {pdf_path}")
|
|
@@ -34,21 +35,17 @@ def create_vector_db_from_pdf(pdf_path):
|
|
| 34 |
except Exception as e:
|
| 35 |
print(f"⚠️ PDF okunurken hata oluştu: {e}")
|
| 36 |
return None
|
| 37 |
-
|
| 38 |
if not text:
|
| 39 |
print("⚠️ PDF'ten metin çıkarılamadı.")
|
| 40 |
return None
|
| 41 |
-
|
| 42 |
print(f"📏 Toplam {len(text)} karakter okundu.")
|
| 43 |
text_splitter = RecursiveCharacterTextSplitter(
|
| 44 |
chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, length_function=len
|
| 45 |
)
|
| 46 |
chunks = text_splitter.split_text(text)
|
| 47 |
print(f"📚 Metin {len(chunks)} parçaya ayrıldı.")
|
| 48 |
-
|
| 49 |
print(f"🔢 Embedding modeli yükleniyor: {EMBEDDING_MODEL_NAME}")
|
| 50 |
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL_NAME, model_kwargs={'device': DEVICE})
|
| 51 |
-
|
| 52 |
print("🧠 FAISS vektör veritabanı oluşturuluyor...")
|
| 53 |
db = FAISS.from_texts(chunks, embeddings)
|
| 54 |
print("✅ Vektör veritabanı başarıyla oluşturuldu.")
|
|
@@ -91,21 +88,16 @@ except Exception as e:
|
|
| 91 |
def get_answer_from_llm(question):
|
| 92 |
if vector_db is None or text_generation_pipeline is None:
|
| 93 |
return "⚠️ Model veya PDF yüklenemedi. Lütfen logları kontrol edin."
|
| 94 |
-
|
| 95 |
print(f"💬 Gelen soru: {question}")
|
| 96 |
try:
|
| 97 |
retrieved_docs = vector_db.similarity_search(question, k=3)
|
| 98 |
except Exception as e:
|
| 99 |
return f"🔎 Vektör arama hatası: {e}"
|
| 100 |
-
|
| 101 |
if not retrieved_docs:
|
| 102 |
return "⚠️ Bu soruyla ilgili belgede bilgi bulunamadı."
|
| 103 |
-
|
| 104 |
context = "\n\n".join([doc.page_content for doc in retrieved_docs])
|
| 105 |
prompt = f"Answer the question based on the following context:\n{context}\n\nQuestion: {question}\nAnswer:"
|
| 106 |
-
|
| 107 |
print("📤 LLM'e gönderilen prompt'un başlangıcı:\n", prompt[:400])
|
| 108 |
-
|
| 109 |
try:
|
| 110 |
outputs = text_generation_pipeline(prompt)
|
| 111 |
final_answer = outputs[0]["generated_text"].strip()
|
|
@@ -115,19 +107,20 @@ def get_answer_from_llm(question):
|
|
| 115 |
return f"Cevap üretilemedi: {e}"
|
| 116 |
|
| 117 |
|
| 118 |
-
# --- 4. Gradio Arayüzü ---
|
| 119 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 120 |
gr.Markdown("# 📘 Fırat Üniversitesi Mevzuat Asistanı")
|
| 121 |
chatbot = gr.Chatbot(label="Sohbet Geçmişi", height=500, type="messages")
|
| 122 |
msg = gr.Textbox(label="Sorunuzu yazın:", placeholder="Örn: MADDE 1’i özetle")
|
| 123 |
|
| 124 |
def user(user_message, history):
|
| 125 |
-
|
|
|
|
| 126 |
|
| 127 |
def bot(history):
|
| 128 |
-
question = history[-1][
|
| 129 |
answer = get_answer_from_llm(question)
|
| 130 |
-
history
|
| 131 |
return history, gr.update(interactive=True)
|
| 132 |
|
| 133 |
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
|
|
|
| 20 |
MAX_NEW_TOKENS = 256
|
| 21 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
|
| 23 |
+
|
| 24 |
# --- 1. PDF'ten Vektör Veritabanı Oluştur ---
|
| 25 |
def create_vector_db_from_pdf(pdf_path):
|
| 26 |
print(f"📄 PDF okunuyor: {pdf_path}")
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
print(f"⚠️ PDF okunurken hata oluştu: {e}")
|
| 37 |
return None
|
|
|
|
| 38 |
if not text:
|
| 39 |
print("⚠️ PDF'ten metin çıkarılamadı.")
|
| 40 |
return None
|
|
|
|
| 41 |
print(f"📏 Toplam {len(text)} karakter okundu.")
|
| 42 |
text_splitter = RecursiveCharacterTextSplitter(
|
| 43 |
chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, length_function=len
|
| 44 |
)
|
| 45 |
chunks = text_splitter.split_text(text)
|
| 46 |
print(f"📚 Metin {len(chunks)} parçaya ayrıldı.")
|
|
|
|
| 47 |
print(f"🔢 Embedding modeli yükleniyor: {EMBEDDING_MODEL_NAME}")
|
| 48 |
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL_NAME, model_kwargs={'device': DEVICE})
|
|
|
|
| 49 |
print("🧠 FAISS vektör veritabanı oluşturuluyor...")
|
| 50 |
db = FAISS.from_texts(chunks, embeddings)
|
| 51 |
print("✅ Vektör veritabanı başarıyla oluşturuldu.")
|
|
|
|
| 88 |
def get_answer_from_llm(question):
|
| 89 |
if vector_db is None or text_generation_pipeline is None:
|
| 90 |
return "⚠️ Model veya PDF yüklenemedi. Lütfen logları kontrol edin."
|
|
|
|
| 91 |
print(f"💬 Gelen soru: {question}")
|
| 92 |
try:
|
| 93 |
retrieved_docs = vector_db.similarity_search(question, k=3)
|
| 94 |
except Exception as e:
|
| 95 |
return f"🔎 Vektör arama hatası: {e}"
|
|
|
|
| 96 |
if not retrieved_docs:
|
| 97 |
return "⚠️ Bu soruyla ilgili belgede bilgi bulunamadı."
|
|
|
|
| 98 |
context = "\n\n".join([doc.page_content for doc in retrieved_docs])
|
| 99 |
prompt = f"Answer the question based on the following context:\n{context}\n\nQuestion: {question}\nAnswer:"
|
|
|
|
| 100 |
print("📤 LLM'e gönderilen prompt'un başlangıcı:\n", prompt[:400])
|
|
|
|
| 101 |
try:
|
| 102 |
outputs = text_generation_pipeline(prompt)
|
| 103 |
final_answer = outputs[0]["generated_text"].strip()
|
|
|
|
| 107 |
return f"Cevap üretilemedi: {e}"
|
| 108 |
|
| 109 |
|
| 110 |
+
# --- 4. Gradio Arayüzü (Yeni mesaj formatıyla uyumlu) ---
|
| 111 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 112 |
gr.Markdown("# 📘 Fırat Üniversitesi Mevzuat Asistanı")
|
| 113 |
chatbot = gr.Chatbot(label="Sohbet Geçmişi", height=500, type="messages")
|
| 114 |
msg = gr.Textbox(label="Sorunuzu yazın:", placeholder="Örn: MADDE 1’i özetle")
|
| 115 |
|
| 116 |
def user(user_message, history):
|
| 117 |
+
history = history + [{"role": "user", "content": user_message}]
|
| 118 |
+
return gr.update(value="", interactive=False), history
|
| 119 |
|
| 120 |
def bot(history):
|
| 121 |
+
question = history[-1]["content"]
|
| 122 |
answer = get_answer_from_llm(question)
|
| 123 |
+
history.append({"role": "assistant", "content": answer})
|
| 124 |
return history, gr.update(interactive=True)
|
| 125 |
|
| 126 |
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|