Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,8 +6,11 @@ from langchain.vectorstores import FAISS
|
|
| 6 |
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 7 |
import os
|
| 8 |
import torch
|
|
|
|
| 9 |
|
| 10 |
# --- 0. Global Ayarlar ---
|
|
|
|
|
|
|
| 11 |
PDF_PATH = "mevzuat.pdf"
|
| 12 |
CHUNK_SIZE = 1000
|
| 13 |
CHUNK_OVERLAP = 150
|
|
@@ -18,9 +21,8 @@ MAX_NEW_TOKENS = 256
|
|
| 18 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 19 |
|
| 20 |
# --- 1. PDF'ten Vektör Veritabanı Oluştur ---
|
| 21 |
-
# Bu fonksiyonda bir değişiklik yok.
|
| 22 |
def create_vector_db_from_pdf(pdf_path):
|
| 23 |
-
print(f"PDF okunuyor: {pdf_path}")
|
| 24 |
text = ""
|
| 25 |
try:
|
| 26 |
with open(pdf_path, "rb") as file:
|
|
@@ -30,112 +32,110 @@ def create_vector_db_from_pdf(pdf_path):
|
|
| 30 |
if page_text:
|
| 31 |
text += f"Sayfa {page_num + 1}:\n{page_text}\n\n"
|
| 32 |
except Exception as e:
|
| 33 |
-
print(f"PDF okunurken hata oluştu: {e}")
|
| 34 |
return None
|
|
|
|
| 35 |
if not text:
|
| 36 |
-
print("PDF'ten metin çıkarılamadı.")
|
| 37 |
return None
|
| 38 |
-
|
|
|
|
| 39 |
text_splitter = RecursiveCharacterTextSplitter(
|
| 40 |
chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, length_function=len
|
| 41 |
)
|
| 42 |
chunks = text_splitter.split_text(text)
|
| 43 |
-
print(f"Metin {len(chunks)} parçaya ayrıldı.")
|
| 44 |
-
|
|
|
|
| 45 |
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL_NAME, model_kwargs={'device': DEVICE})
|
| 46 |
-
|
|
|
|
| 47 |
db = FAISS.from_texts(chunks, embeddings)
|
| 48 |
-
print("Vektör veritabanı başarıyla oluşturuldu.")
|
| 49 |
return db
|
| 50 |
|
|
|
|
| 51 |
vector_db = None
|
| 52 |
if os.path.exists(PDF_PATH):
|
| 53 |
vector_db = create_vector_db_from_pdf(PDF_PATH)
|
| 54 |
else:
|
| 55 |
-
print(f"Hata: {PDF_PATH} bulunamadı. Lütfen PDF dosyasını yükleyin.")
|
|
|
|
| 56 |
|
| 57 |
# --- 2. LLM Yükleme ---
|
| 58 |
-
# Bu bölümde bir değişiklik yok.
|
| 59 |
text_generation_pipeline = None
|
| 60 |
try:
|
| 61 |
-
print(f"Model yükleniyor: {LLM_MODEL_NAME} -> Cihaz: {DEVICE}")
|
| 62 |
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
| 63 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
text_generation_pipeline = pipeline(
|
| 69 |
"text2text-generation",
|
| 70 |
model=model,
|
| 71 |
tokenizer=tokenizer,
|
| 72 |
device=device_id,
|
| 73 |
-
|
| 74 |
)
|
| 75 |
-
print("LLM pipeline başarıyla oluşturuldu.")
|
| 76 |
except Exception as e:
|
| 77 |
-
print(f"LLM yüklenirken hata oluştu: {e}")
|
| 78 |
text_generation_pipeline = None
|
| 79 |
|
| 80 |
-
|
| 81 |
-
#
|
| 82 |
-
# Sadece soruyu alıp, cevabı bir metin olarak döndürüyor.
|
| 83 |
def get_answer_from_llm(question):
|
| 84 |
if vector_db is None or text_generation_pipeline is None:
|
| 85 |
-
return "Model veya PDF yüklenemedi. Lütfen logları kontrol edin."
|
| 86 |
|
| 87 |
-
print(f"Gelen soru: {question}")
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
if not retrieved_docs:
|
| 92 |
-
return "Bu soruyla ilgili belgede bilgi bulunamadı."
|
| 93 |
|
| 94 |
context = "\n\n".join([doc.page_content for doc in retrieved_docs])
|
| 95 |
-
|
| 96 |
-
# DÜZELTME 2: Prompt'u daha basit ve net hale getirdik.
|
| 97 |
-
# Modelin kafasını karıştıracak "Soru:", "Bağlam:" gibi kelimeleri sadeleştirdik.
|
| 98 |
prompt = f"Answer the question based on the following context:\n{context}\n\nQuestion: {question}\nAnswer:"
|
| 99 |
|
| 100 |
-
print("LLM'e gönderilen prompt'un başlangıcı:", prompt[:
|
| 101 |
|
| 102 |
try:
|
| 103 |
outputs = text_generation_pipeline(prompt)
|
| 104 |
final_answer = outputs[0]["generated_text"].strip()
|
| 105 |
return final_answer
|
| 106 |
except Exception as e:
|
| 107 |
-
print("Cevap üretilirken hata:", e)
|
| 108 |
return f"Cevap üretilemedi: {e}"
|
| 109 |
|
| 110 |
-
|
|
|
|
| 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)
|
| 114 |
msg = gr.Textbox(label="Sorunuzu yazın:", placeholder="Örn: MADDE 1’i özetle")
|
| 115 |
|
| 116 |
-
# DÜZELTME 1: Sohbet mantığını tamamen düzelttik.
|
| 117 |
-
# Bu yeni yapı, Gradio ile chatbot yapmak için doğru yöntemdir.
|
| 118 |
-
|
| 119 |
-
# 1. Adım: Kullanıcı mesajını gönderir. Mesaj kutusu temizlenir ve pasif hale gelir.
|
| 120 |
-
# Sohbet geçmişine [kullanıcı_mesajı, None] eklenir.
|
| 121 |
def user(user_message, history):
|
| 122 |
return gr.update(value="", interactive=False), history + [[user_message, None]]
|
| 123 |
|
| 124 |
-
# 2. Adım: Model cevabı üretir ve sohbet geçmişindeki "None" olan yeri doldurur.
|
| 125 |
-
# Cevap gelince mesaj kutusu tekrar aktif hale gelir.
|
| 126 |
def bot(history):
|
| 127 |
question = history[-1][0]
|
| 128 |
answer = get_answer_from_llm(question)
|
| 129 |
history[-1][1] = answer
|
| 130 |
return history, gr.update(interactive=True)
|
| 131 |
|
| 132 |
-
# Enter veya butona basıldığında user fonksiyonu, ardından bot fonksiyonu çalışır.
|
| 133 |
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 134 |
bot, chatbot, [chatbot, msg]
|
| 135 |
)
|
| 136 |
-
|
| 137 |
-
clear_btn = gr.Button("Sohbeti Temizle")
|
| 138 |
clear_btn.click(lambda: (None, []), None, [msg, chatbot], queue=False)
|
| 139 |
|
| 140 |
if __name__ == "__main__":
|
| 141 |
-
demo.launch(debug=True)
|
|
|
|
| 6 |
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 7 |
import os
|
| 8 |
import torch
|
| 9 |
+
import warnings
|
| 10 |
|
| 11 |
# --- 0. Global Ayarlar ---
|
| 12 |
+
warnings.filterwarnings("ignore", message="The following encoder weights")
|
| 13 |
+
|
| 14 |
PDF_PATH = "mevzuat.pdf"
|
| 15 |
CHUNK_SIZE = 1000
|
| 16 |
CHUNK_OVERLAP = 150
|
|
|
|
| 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}")
|
| 26 |
text = ""
|
| 27 |
try:
|
| 28 |
with open(pdf_path, "rb") as file:
|
|
|
|
| 32 |
if page_text:
|
| 33 |
text += f"Sayfa {page_num + 1}:\n{page_text}\n\n"
|
| 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.")
|
| 55 |
return db
|
| 56 |
|
| 57 |
+
|
| 58 |
vector_db = None
|
| 59 |
if os.path.exists(PDF_PATH):
|
| 60 |
vector_db = create_vector_db_from_pdf(PDF_PATH)
|
| 61 |
else:
|
| 62 |
+
print(f"⚠️ Hata: {PDF_PATH} bulunamadı. Lütfen PDF dosyasını yükleyin.")
|
| 63 |
+
|
| 64 |
|
| 65 |
# --- 2. LLM Yükleme ---
|
|
|
|
| 66 |
text_generation_pipeline = None
|
| 67 |
try:
|
| 68 |
+
print(f"🤖 Model yükleniyor: {LLM_MODEL_NAME} -> Cihaz: {DEVICE}")
|
| 69 |
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
| 70 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(LLM_MODEL_NAME, torch_dtype=torch.float32)
|
| 71 |
+
if DEVICE == "cuda":
|
| 72 |
+
model.to("cuda")
|
| 73 |
+
device_id = 0
|
| 74 |
+
else:
|
| 75 |
+
device_id = -1
|
| 76 |
+
|
| 77 |
text_generation_pipeline = pipeline(
|
| 78 |
"text2text-generation",
|
| 79 |
model=model,
|
| 80 |
tokenizer=tokenizer,
|
| 81 |
device=device_id,
|
| 82 |
+
max_new_tokens=MAX_NEW_TOKENS
|
| 83 |
)
|
| 84 |
+
print("✅ LLM pipeline başarıyla oluşturuldu.")
|
| 85 |
except Exception as e:
|
| 86 |
+
print(f"❌ LLM yüklenirken hata oluştu: {e}")
|
| 87 |
text_generation_pipeline = None
|
| 88 |
|
| 89 |
+
|
| 90 |
+
# --- 3. Soru-Cevap Fonksiyonu ---
|
|
|
|
| 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()
|
| 112 |
return final_answer
|
| 113 |
except Exception as e:
|
| 114 |
+
print("⚠️ Cevap üretilirken hata:", e)
|
| 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 |
return gr.update(value="", interactive=False), history + [[user_message, None]]
|
| 126 |
|
|
|
|
|
|
|
| 127 |
def bot(history):
|
| 128 |
question = history[-1][0]
|
| 129 |
answer = get_answer_from_llm(question)
|
| 130 |
history[-1][1] = answer
|
| 131 |
return history, gr.update(interactive=True)
|
| 132 |
|
|
|
|
| 133 |
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 134 |
bot, chatbot, [chatbot, msg]
|
| 135 |
)
|
| 136 |
+
|
| 137 |
+
clear_btn = gr.Button("🧹 Sohbeti Temizle")
|
| 138 |
clear_btn.click(lambda: (None, []), None, [msg, chatbot], queue=False)
|
| 139 |
|
| 140 |
if __name__ == "__main__":
|
| 141 |
+
demo.launch(debug=True)
|