|
import gradio as gr |
|
import json |
|
from transformers import pipeline |
|
|
|
|
|
chatbot = pipeline("question-answering", model="savasy/bert-base-turkish-squad") |
|
|
|
|
|
def load_json(file): |
|
if file is None: |
|
return "JSON dosyası yükleyin." |
|
try: |
|
|
|
with open(file, "r", encoding="utf-8") as f: |
|
data = json.load(f) |
|
return data |
|
except UnicodeDecodeError: |
|
|
|
try: |
|
with open(file, "r", encoding="windows-1254") as f: |
|
data = json.load(f) |
|
return data |
|
except Exception as e: |
|
return f"Hata: Dosya kodlaması uyumsuz: {e}" |
|
except Exception as e: |
|
return f"Hata: {e}" |
|
|
|
|
|
def chat_with_bot(user_input, json_file): |
|
|
|
json_data = load_json(json_file) |
|
|
|
if isinstance(json_data, str): |
|
return json_data |
|
|
|
|
|
context = json.dumps(json_data, ensure_ascii=False) |
|
|
|
|
|
if "isimleri neler" in user_input.lower() or "isimler" in user_input.lower(): |
|
if isinstance(json_data, list): |
|
names = [entry.get("İsim", "Bilinmiyor") for entry in json_data if "İsim" in entry] |
|
if names: |
|
return f"JSON dosyasındaki isimler: {', '.join(names)}" |
|
else: |
|
return "JSON dosyasında isim bulunamadı." |
|
return "JSON dosyası bir liste değil, isimler çıkarılamadı." |
|
|
|
|
|
try: |
|
response = chatbot(question=user_input, context=context) |
|
bot_reply = response["answer"] |
|
confidence = response["score"] |
|
bot_reply += f" (Güven skoru: {confidence:.2f})" |
|
except Exception as e: |
|
bot_reply = f"Hata: Model yanıtı üretirken bir sorun oluştu: {e}" |
|
|
|
|
|
if "kaç kişi" in user_input.lower(): |
|
num_people = len(json_data) |
|
bot_reply += f" JSON dosyasındaki kişi sayısı: {num_people}." |
|
|
|
if "yaş" in user_input.lower() and isinstance(json_data, list): |
|
ages = [entry['Yaş'] for entry in json_data if 'Yaş' in entry] |
|
avg_age = sum(ages) / len(ages) if ages else "bulunamadı" |
|
bot_reply += f" JSON dosyasındaki ortalama yaş: {avg_age}." |
|
|
|
return bot_reply |
|
|
|
|
|
demo = gr.Interface( |
|
fn=chat_with_bot, |
|
inputs=[ |
|
gr.Textbox(label="💬 Senin Mesajın", placeholder="Örneğin: 'JSON dosyası isimleri neler?'"), |
|
gr.File(label="📂 JSON Dosyası", type="filepath", file_types=[".json"]), |
|
], |
|
outputs="text", |
|
title="🧠 Türkçe Sohbet Botu ve JSON Entegrasyonu", |
|
description="JSON dosyasındaki verilerle Türkçe sorular sorarak doğal dilde cevaplar alın.", |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch() |