Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,10 +15,13 @@ PDF_PATH = "mevzuat.pdf"
|
|
| 15 |
CHUNK_SIZE = 1000
|
| 16 |
CHUNK_OVERLAP = 150
|
| 17 |
EMBEDDING_MODEL_NAME = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
|
|
|
|
|
|
| 18 |
LLM_MODEL_NAME = "mrm8488/bert2bert_shared-turkish-summarization"
|
| 19 |
|
| 20 |
MAX_NEW_TOKENS = 700
|
| 21 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
# --- 1. PDF'ten Vektör Veritabanı Oluştur ---
|
|
@@ -35,17 +38,21 @@ def create_vector_db_from_pdf(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.")
|
|
@@ -64,18 +71,16 @@ text_generation_pipeline = None
|
|
| 64 |
try:
|
| 65 |
print(f"🤖 Model yükleniyor: {LLM_MODEL_NAME} -> Cihaz: {DEVICE}")
|
| 66 |
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
| 67 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
device_id = -1
|
| 73 |
|
| 74 |
text_generation_pipeline = pipeline(
|
| 75 |
"text2text-generation",
|
| 76 |
model=model,
|
| 77 |
tokenizer=tokenizer,
|
| 78 |
-
device=device_id,
|
| 79 |
max_new_tokens=MAX_NEW_TOKENS
|
| 80 |
)
|
| 81 |
print("✅ LLM pipeline başarıyla oluşturuldu.")
|
|
@@ -88,16 +93,22 @@ except Exception as e:
|
|
| 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,9 +118,10 @@ def get_answer_from_llm(question):
|
|
| 107 |
return f"Cevap üretilemedi: {e}"
|
| 108 |
|
| 109 |
|
| 110 |
-
# --- 4. Gradio Arayüzü
|
| 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 |
|
|
|
|
| 15 |
CHUNK_SIZE = 1000
|
| 16 |
CHUNK_OVERLAP = 150
|
| 17 |
EMBEDDING_MODEL_NAME = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
| 18 |
+
|
| 19 |
+
# Daha stabil model kullanımı (dilersen eski modeli geri koyabilirsin)
|
| 20 |
LLM_MODEL_NAME = "mrm8488/bert2bert_shared-turkish-summarization"
|
| 21 |
|
| 22 |
MAX_NEW_TOKENS = 700
|
| 23 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
+
MAX_CONTEXT_LENGTH = 4000
|
| 25 |
|
| 26 |
|
| 27 |
# --- 1. PDF'ten Vektör Veritabanı Oluştur ---
|
|
|
|
| 38 |
except Exception as e:
|
| 39 |
print(f"⚠️ PDF okunurken hata oluştu: {e}")
|
| 40 |
return None
|
| 41 |
+
|
| 42 |
if not text:
|
| 43 |
print("⚠️ PDF'ten metin çıkarılamadı.")
|
| 44 |
return None
|
| 45 |
+
|
| 46 |
print(f"📏 Toplam {len(text)} karakter okundu.")
|
| 47 |
text_splitter = RecursiveCharacterTextSplitter(
|
| 48 |
chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, length_function=len
|
| 49 |
)
|
| 50 |
chunks = text_splitter.split_text(text)
|
| 51 |
print(f"📚 Metin {len(chunks)} parçaya ayrıldı.")
|
| 52 |
+
|
| 53 |
print(f"🔢 Embedding modeli yükleniyor: {EMBEDDING_MODEL_NAME}")
|
| 54 |
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL_NAME, model_kwargs={'device': DEVICE})
|
| 55 |
+
|
| 56 |
print("🧠 FAISS vektör veritabanı oluşturuluyor...")
|
| 57 |
db = FAISS.from_texts(chunks, embeddings)
|
| 58 |
print("✅ Vektör veritabanı başarıyla oluşturuldu.")
|
|
|
|
| 71 |
try:
|
| 72 |
print(f"🤖 Model yükleniyor: {LLM_MODEL_NAME} -> Cihaz: {DEVICE}")
|
| 73 |
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
| 74 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 75 |
+
LLM_MODEL_NAME,
|
| 76 |
+
torch_dtype=torch.float32,
|
| 77 |
+
device_map="auto" # 🔥 model meta değil, gerçek cihaza yüklenir
|
| 78 |
+
)
|
|
|
|
| 79 |
|
| 80 |
text_generation_pipeline = pipeline(
|
| 81 |
"text2text-generation",
|
| 82 |
model=model,
|
| 83 |
tokenizer=tokenizer,
|
|
|
|
| 84 |
max_new_tokens=MAX_NEW_TOKENS
|
| 85 |
)
|
| 86 |
print("✅ LLM pipeline başarıyla oluşturuldu.")
|
|
|
|
| 93 |
def get_answer_from_llm(question):
|
| 94 |
if vector_db is None or text_generation_pipeline is None:
|
| 95 |
return "⚠️ Model veya PDF yüklenemedi. Lütfen logları kontrol edin."
|
| 96 |
+
|
| 97 |
print(f"💬 Gelen soru: {question}")
|
| 98 |
try:
|
| 99 |
retrieved_docs = vector_db.similarity_search(question, k=3)
|
| 100 |
except Exception as e:
|
| 101 |
return f"🔎 Vektör arama hatası: {e}"
|
| 102 |
+
|
| 103 |
if not retrieved_docs:
|
| 104 |
return "⚠️ Bu soruyla ilgili belgede bilgi bulunamadı."
|
| 105 |
+
|
| 106 |
context = "\n\n".join([doc.page_content for doc in retrieved_docs])
|
| 107 |
+
context = context[:MAX_CONTEXT_LENGTH] # 🔥 uzun metinleri kısalt
|
| 108 |
prompt = f"Answer the question based on the following context:\n{context}\n\nQuestion: {question}\nAnswer:"
|
| 109 |
+
|
| 110 |
print("📤 LLM'e gönderilen prompt'un başlangıcı:\n", prompt[:400])
|
| 111 |
+
|
| 112 |
try:
|
| 113 |
outputs = text_generation_pipeline(prompt)
|
| 114 |
final_answer = outputs[0]["generated_text"].strip()
|
|
|
|
| 118 |
return f"Cevap üretilemedi: {e}"
|
| 119 |
|
| 120 |
|
| 121 |
+
# --- 4. Gradio Arayüzü ---
|
| 122 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 123 |
gr.Markdown("# 📘 Fırat Üniversitesi Mevzuat Asistanı")
|
| 124 |
+
|
| 125 |
chatbot = gr.Chatbot(label="Sohbet Geçmişi", height=500, type="messages")
|
| 126 |
msg = gr.Textbox(label="Sorunuzu yazın:", placeholder="Örn: MADDE 1’i özetle")
|
| 127 |
|