vizsum-pro / summarizer.py
Vartex39's picture
🔥 Yeni UI entegrasyonu: RAG + geçmiş + özetleme
4c198b1
import os
import requests
from dotenv import load_dotenv
from utils import chunk_text_by_tokens
load_dotenv()
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key or not api_key.strip():
raise RuntimeError("❌ OPENROUTER_API_KEY bulunamadı. Hugging Face Secrets kısmına eklenmeli.")
class SummaryException(Exception):
pass
def build_prompt(text, mode, lang_mode="Otomatik", is_table=False, model_name=""):
lang_instruction = ""
if lang_mode == "Türkçeye Çevir":
lang_instruction = "\n\nSonuç Türkçeye çevrilsin."
elif lang_mode == "İngilizceye Çevir":
lang_instruction = "\n\nSonuç İngilizceye çevrilsin."
if is_table:
instruction = "Aşağıdaki tabloyu analiz et ve teknik bir şekilde özetle."
return f"{instruction}{lang_instruction}\n\n{text}"
if "Karma" in mode:
instruction = """
Aşağıdaki metni 3 ayrı biçimde özetle:
1. Teknik bir özet ver.
2. Herkesin anlayacağı şekilde sade bir açıklama yaz.
3. Madde madde önemli notları çıkar.
"""
elif "Sade" in mode:
instruction = "Bu metni herkesin anlayacağı şekilde sadeleştir."
elif "Eleştir" in mode:
instruction = "Metni eleştir, eksik ve güçlü yönlerini değerlendir."
elif "Başlık" in mode:
instruction = "Metne uygun başlık önerileri üret."
elif "Not" in mode:
instruction = "Bu metinden önemli notlar çıkar."
elif "Chat" in mode:
instruction = """
Aşağıdaki yazışmaları veya serbest notları oku ve şunları çıkar:
- Ana konuşma başlıkları
- Varsa karar verilen noktalar
- Belirgin fikir veya öneriler
Yazım sade ve maddeli olsun.
"""
else:
instruction = "Metni kısa ve teknik bir şekilde özetle."
return f"{instruction}{lang_instruction}\n\nMetin:\n{text}"
def summarize_text(text, mode, model_name="anthropic/claude-3-haiku", lang_mode="Otomatik", is_table=False):
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key.strip()}",
"Content-Type": "application/json"
}
prompt = build_prompt(text, mode, lang_mode, is_table, model_name)
payload = {
"model": model_name,
"messages": [
{"role": "user", "content": prompt}
],
"max_tokens": 500
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
result = response.json()
return result['choices'][0]['message']['content'].strip()
except requests.exceptions.HTTPError as e:
raise SummaryException(f"❌ HTTP Hatası: {e} | Yanıt: {response.text}")
except Exception as e:
raise SummaryException(f"❌ Sistemsel Hata: {str(e)}")
def summarize_long_text(text, mode, model_name="anthropic/claude-3-haiku", lang_mode="Otomatik", is_table=False):
chunks = chunk_text_by_tokens(text, max_tokens=800)
summaries = []
for chunk in chunks:
try:
summary = summarize_text(chunk, mode, model_name, lang_mode, is_table)
summaries.append(summary)
except SummaryException as e:
summaries.append(str(e))
return "\n\n".join(summaries)
def generate_answer(query, source_tuples, chat_history=None, model_name="anthropic/claude-3-haiku"):
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key.strip()}",
"Content-Type": "application/json"
}
context_block = "\n\n".join([f"({i+1}) {txt}" for i, (_, txt) in enumerate(source_tuples)])
history_prompt = ""
if chat_history:
for q, a in chat_history:
history_prompt += f"Q: {q}\nA: {a}\n\n"
prompt = f"""{history_prompt}
Aşağıdaki kaynak metinlere dayanarak kullanıcıdan gelen soruyu yanıtla:
{context_block}
Soru: {query}
Yanıt:"""
payload = {
"model": model_name,
"messages": [
{"role": "user", "content": prompt.strip()}
],
"max_tokens": 1500
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
result = response.json()
return result['choices'][0]['message']['content'].strip()
except requests.exceptions.HTTPError as e:
raise SummaryException(f"❌ HTTP Hatası: {e} | Yanıt: {response.text}")
except Exception as e:
raise SummaryException(f"❌ Sistemsel Hata: {str(e)}")