File size: 3,986 Bytes
efc4680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import argparse
import gradio as gr
import dotenv
from app.retrieval import get_answer, DRUG_IDS, _normalize

dotenv.load_dotenv()

DRUG_LIST_SORTED = sorted(DRUG_IDS, key=_normalize)
DRUG_NORMALIZED = [(d, _normalize(d)) for d in DRUG_LIST_SORTED]
DRUG_COUNT = len(DRUG_LIST_SORTED)
MAX_LIST_DISPLAY = 100


def filter_drugs(query: str) -> str:
    q = _normalize(query or "").strip()
    if not q:
        shown = DRUG_LIST_SORTED[:MAX_LIST_DISPLAY]
        body = "\n".join(f"- {d}" for d in shown)
        if DRUG_COUNT > MAX_LIST_DISPLAY:
            body += f"\n\n_İlk {len(shown)} ilaç gösteriliyor (toplam {DRUG_COUNT}). Daraltmak için yukarıya yazın._"
        return body
    matches = [d for d, n in DRUG_NORMALIZED if q in n]
    if not matches:
        return f"_Eşleşme bulunamadı: **{query}**_"
    shown = matches[:MAX_LIST_DISPLAY]
    body = "\n".join(f"- {d}" for d in shown)
    if len(matches) > MAX_LIST_DISPLAY:
        body += f"\n\n_{len(shown)} / {len(matches)} sonuç gösteriliyor._"
    else:
        body += f"\n\n_{len(matches)} sonuç_"
    return body

def chat_interface(message, history):
    if not message:
        return ""

    # RAG sistemi 3 parametre dönüyor (Cevap, İlaç ID, Kullanılan Chunklar).
    answer, drug_id, chunks_str = get_answer(message, history)

    final_response = answer

    # Text chunklarını Colab hücresinin çıktısına (console) yazdırıyoruz
    """if chunks_str:
        print("\n" + "="*60)
        print(f"🧐 KULLANICI SORUSU: {message}")
        print("-" * 60)
        print(f"📄 MODELE GÖNDERİLEN KAYNAK METİNLER (CHUNKLAR):\n\n{chunks_str}")
        print("="*60 + "\n")  """

    return final_response

FORCE_DARK_JS = """
() => {
    const url = new URL(window.location);
    if (url.searchParams.get('__theme') !== 'dark') {
        url.searchParams.set('__theme', 'dark');
        window.location.href = url.href;
    }
}
"""


# Module-level demo — `gradio app/ui.py` ile hot-reload için gerekli
with gr.Blocks(title="İlaç KT Chatbot", theme=gr.themes.Default(), js=FORCE_DARK_JS) as demo:
    gr.Markdown("## İlaç Sohbet Botu RAG Q&A")

    gr.Markdown("""
    ⚠️ İLAC ADLARINI YAZARKEN DOĞRU ŞEKİLDE YAZIN. BU SAYEDE SİSTEMİN DOĞRU KULLANMA TALİMATI BELGESİNİ BULMASI VE DOĞRU CEVAPLAR VERMESİ DAHA MUHTEMEL OLUR. ÖRNEK SORU: **Parol hamilelikte kullanılır mı?**

    ⚠️ Bu asistan yalnızca geliştirme amaçlıdır. Her tıbbi karar öncesinde mutlaka doktorunuza veya eczacınıza danışın.

    """)

    gr.Markdown(
        f"""📋 Sistemimiz şu anda **{DRUG_COUNT}** TABLET ilacın resmî Kullanma Talimatı (KT) belgesini işliyor.\n
Kullanılan model gemini-flash-latest free tier olduğu için, günlük istek limiti bulunmakta bu nedenle bazen cevap veremeyebilir."""
    )

    with gr.Accordion("İşlenen ilaçların tam listesi", open=False):
        drug_search = gr.Textbox(
            placeholder="İlaç ara... (örn: parol)",
            show_label=False,
            container=False,
        )
        drug_list_view = gr.Markdown(filter_drugs(""))
        drug_search.change(fn=filter_drugs, inputs=drug_search, outputs=drug_list_view)

    gr.ChatInterface(
        fn=chat_interface,
        chatbot=gr.Chatbot(height=400),
        textbox=gr.Textbox(placeholder="İlacın adını belirterek sorunuzu girin... (Örn: Parol hamilelikte kullanılır mı?)", container=False, scale=7),
        title="Sadece İlaç KT PDF'lerine Dayanarak Cevap Veren Asistan",
    )


def main(host, port, share=False):
    demo.launch(server_name=host, server_port=port, share=share)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", type=str, default="0.0.0.0")
    parser.add_argument("--port", type=int, default=7860)
    parser.add_argument("--share", action="store_true", help="Create a public link for Gradio")
    args = parser.parse_args()
    main(args.host, args.port, True)