File size: 5,607 Bytes
2789db4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import sqlite3
import pandas as pd
import plotly.express as px
import random
import json
import os
from datetime import datetime
from transformers import pipeline

# --- DB & MODEL SETUP ---
def init_db():
    conn = sqlite3.connect('faithpath.db')
    conn.execute('CREATE TABLE IF NOT EXISTS journal_entries (id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, entry_text TEXT, detected_emotion TEXT, mission_source TEXT, mission_text TEXT, city TEXT)')
    conn.commit(); conn.close()

init_db()
sentiment_analyzer = pipeline('sentiment-analysis', model='savasy/bert-base-turkish-sentiment-cased')

with open('faith_library_final_v56.json', 'r', encoding='utf-8') as f:
    faith_library = json.load(f)

def semantic_engine(metin):
    t = metin.lower()
    logic = {
        'öfke_ve_gerginlik': ['nevrim döndü', 'parlamamak', 'zor tutuyorum', 'damarıma bas', 'tepemin tasını'],
        'şükran_ve_minnet': ['secde-i şükran', 'hamdolsun', 'minnettarım', 'allah bin bereket'],
        'sabır_ve_metanet': ['bağrıma taş bastım', 'isyan etmeksizin', 'dişini sıkıp', 'sabır taşı'],
        'cömertlik_ve_paylaşma': ['rızkı paylaştıkça', 'ihtiyacı olana', 'infak etmek', 'sadaka']
    }
    for cat, words in logic.items():
        if any(w in t for w in words): return cat, random.choice(faith_library.get(cat, []))
    res = sentiment_analyzer(metin)[0]
    cat = 'mutluluk_ve_huzur' if res['label'] == 'positive' else 'hüzün_ve_keder'
    return cat, random.choice(faith_library.get(cat, []))

def process_user(text):
    if len(text.strip()) < 10: return "<div style='padding:20px; background:#7f1d1d; color:white; border-radius:10px;'>Hata: Analiz için daha detaylı bir cümle yazmalısınız.</div>"
    cat, mission = semantic_engine(text)
    conn = sqlite3.connect('faithpath.db')
    conn.execute('INSERT INTO journal_entries (date, entry_text, detected_emotion, mission_source, mission_text, city) VALUES (?,?,?,?,?,?)',
                 (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), text, cat, mission['kaynak'], mission['metin'], 'Belirtilmemiş'))
    conn.commit(); conn.close()

    return f"""<div style='padding:30px; border-radius:20px; background:#0f172a; border:2px solid #10b981; color:white; font-family:sans-serif;'>
        <h2 style='color:#10b981; text-align:center; margin-top:0;'>🕊️ Manevi Rehberlik</h2>
        <div style='background:#1e293b; padding:20px; border-radius:15px; margin:20px 0; border-left:6px solid #3b82f6;'>
            <p style='color:#94a3b8; font-size:0.8em; text-transform:uppercase; margin-bottom:5px;'>Sistem Analizi: {cat.replace('_',' ').title()}</p>
            <p style='font-size:1.3em; font-style:italic; line-height:1.5;'>"{mission['metin']}"</p>
            <p style='text-align:right; color:#10b981; font-weight:bold;'>— {mission['kaynak']}</p>
        </div>
        <div style='background:#064e3b; padding:20px; border-radius:15px; border-left:6px solid #fbbf24;'>
            <strong style='color:#fbbf24; display:block; margin-bottom:8px; font-size:1.1em;'>🎯 Bugünün Kalp Görevi:</strong>
            <p style='font-size:1.1em; line-height:1.4;'>{mission.get('rehber_mesaji', 'Ailenizle vakit geçirin.')}</p>
        </div>
    </div>"""

def get_admin(pwd):
    if pwd != 'Enes.13112006': return gr.update(visible=False), None, None, "### Hata: Yetkisiz Erişim"
    conn = sqlite3.connect('faithpath.db'); df = pd.read_sql_query('SELECT * FROM journal_entries ORDER BY id DESC', conn); conn.close()
    if df.empty: return gr.update(visible=True), None, None, "Veri yok."
    
    # Plot 1: Sentiment Distribution
    fig_pie = px.pie(df, names='detected_emotion', title='Genel Duygu Dağılımı', template='plotly_dark', hole=.4)
    
    # Plot 2: Time Trend (DD/MM/YYYY)
    df['date_dt'] = pd.to_datetime(df['date'])
    trend_df = df.groupby(df['date_dt'].dt.date).size().reset_index(name='Sayi')
    fig_line = px.line(trend_df, x='date_dt', y='Sayi', title='Kayıt Trendi', template='plotly_dark', markers=True)
    fig_line.update_xaxes(tickformat="%d/%m/%Y")

    table = df[['date', 'entry_text', 'detected_emotion']].to_html(classes='table table-dark table-hover', index=False)
    return gr.update(visible=True), fig_pie, fig_line, f"### Toplam Kayıt: {len(df)}\n{table}"

# --- UI DESIGN ---
with gr.Blocks(theme=gr.themes.Soft(), css='.gradio-container {background-color: #0f172a}') as demo:
    gr.Markdown("<h1 style='text-align:center; color:#10b981;'>🕊️ FaithPath Professional v5.8.8</h1>")
    with gr.Tabs():
        with gr.Tab('🕊️ Rehberlik Asistanı'):
            with gr.Row():
                with gr.Column(scale=2):
                    txt = gr.Textbox(label='Bugün ailenizle ilgili neler yaşadınız?', placeholder='Duygularınızı buraya yazın...', lines=10)
                    btn = gr.Button('Analiz Et ve Rehberlik Al', variant='primary')
                with gr.Column(scale=3): out = gr.HTML()
            btn.click(process_user, [txt], out)
        with gr.Tab('📊 Yönetici Paneli'):
            with gr.Row():
                pwd = gr.Textbox(label='Yönetici Şifresi', type='password'); lbtn = gr.Button('Sisteme Giriş')
            with gr.Column(visible=False) as zone:
                with gr.Row():
                    plt1 = gr.Plot(); plt2 = gr.Plot()
                stats = gr.HTML()
            lbtn.click(get_admin, pwd, [zone, plt1, plt2, stats])
    gr.Markdown("<center style='color:#64748b; margin-top:20px;'>Enes YILMAZ - Karabük University | Time Analysis & Simplified UI</center>")
demo.launch()