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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import sqlite3
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import random
|
| 6 |
+
import re
|
| 7 |
+
import torch
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from transformers import pipeline
|
| 12 |
+
|
| 13 |
+
# --- DATABASE INITIALIZATION ---
|
| 14 |
+
def init_db():
|
| 15 |
+
conn = sqlite3.connect('faithpath.db')
|
| 16 |
+
cursor = conn.cursor()
|
| 17 |
+
cursor.execute('''
|
| 18 |
+
CREATE TABLE IF NOT EXISTS journal_entries (
|
| 19 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 20 |
+
date TEXT,
|
| 21 |
+
entry_text TEXT,
|
| 22 |
+
detected_emotion TEXT,
|
| 23 |
+
mission_source TEXT,
|
| 24 |
+
mission_text TEXT,
|
| 25 |
+
city TEXT
|
| 26 |
+
)
|
| 27 |
+
''')
|
| 28 |
+
conn.commit()
|
| 29 |
+
conn.close()
|
| 30 |
+
|
| 31 |
+
init_db()
|
| 32 |
+
|
| 33 |
+
# --- MODEL & LIBRARY LOADING ---
|
| 34 |
+
sentiment_analyzer = pipeline('sentiment-analysis', model='savasy/bert-base-turkish-sentiment-cased')
|
| 35 |
+
|
| 36 |
+
if os.path.exists('faith_library_final_v56.json'):
|
| 37 |
+
with open('faith_library_final_v56.json', 'r', encoding='utf-8') as f:
|
| 38 |
+
faith_library = json.load(f)
|
| 39 |
+
else:
|
| 40 |
+
faith_library = {}
|
| 41 |
+
|
| 42 |
+
# --- CORE ENGINE ---
|
| 43 |
+
def semantic_bridge_engine(metin):
|
| 44 |
+
text_lower = metin.lower()
|
| 45 |
+
exclusive_logic = {
|
| 46 |
+
"öfke_ve_gerginlik": ["sabrımın son kertesindeyim", "bendini aşan", "yanardağ gibiyim", "tepemin tasını", "damarıma bas", "nevrim döndü", "parlamamak", "zor tutuyorum"],
|
| 47 |
+
"şükran_ve_minnet": ["secde-i şükran", "selamet kapısı", "bereketli lokma", "nimetlerin kadrini", "hamd etsek az", "minnettarım", "şükür secdesine", "allah bin bereket", "halimize bin şükür"],
|
| 48 |
+
"sabır_ve_metanet": ["bağrıma taş basıp", "bağrıma taş bastım", "isyan etmeksizin", "metanetimi koruyarak", "dişini sıkıp", "sıramı bekleyerek", "zamanın değirmeninde", "sabır taşı"],
|
| 49 |
+
"cömertlik_ve_paylaşma": ["rızkı paylaştıkça", "ihtiyacı olana", "gönlümüzü açtık", "infak etmek", "sadaka vermek", "ikramda bulunmak"]
|
| 50 |
+
}
|
| 51 |
+
for cat, words in exclusive_logic.items():
|
| 52 |
+
if any(w in text_lower for w in words):
|
| 53 |
+
return cat, random.choice(faith_library.get(cat, []))
|
| 54 |
+
|
| 55 |
+
bert_res = sentiment_analyzer(metin)[0]
|
| 56 |
+
cat = "mutluluk_ve_huzur" if bert_res['label'] == 'positive' else "hüzün_ve_keder"
|
| 57 |
+
return cat, random.choice(faith_library.get(cat, []))
|
| 58 |
+
|
| 59 |
+
# --- UI FUNCTIONS ---
|
| 60 |
+
def process_entry_user(text):
|
| 61 |
+
if len(text.strip()) < 10:
|
| 62 |
+
return "<div style='padding:20px; background:#7f1d1d; color:white; border-radius:10px;'>Hata: Analiz için en az bir cümle yazmalısınız.</div>"
|
| 63 |
+
|
| 64 |
+
cat, mission = semantic_bridge_engine(text)
|
| 65 |
+
cat_title = cat.replace('_', ' ').title()
|
| 66 |
+
|
| 67 |
+
conn = sqlite3.connect('faithpath.db')
|
| 68 |
+
cursor = conn.cursor()
|
| 69 |
+
cursor.execute('''
|
| 70 |
+
INSERT INTO journal_entries (date, entry_text, detected_emotion, mission_source, mission_text, city)
|
| 71 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 72 |
+
''', (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), text, cat, mission['kaynak'], mission['metin'], "Halk Erişimi"))
|
| 73 |
+
conn.commit()
|
| 74 |
+
conn.close()
|
| 75 |
+
|
| 76 |
+
return f""
|
| 77 |
+
<div style='padding: 25px; border-radius: 15px; background-color: #0f172a; border: 2px solid #10b981; color: white;'>
|
| 78 |
+
<h2 style='color: #10b981; text-align: center;'>🕊️ Manevi Rehberlik</h2>
|
| 79 |
+
<div style='background: #1e293b; padding: 15px; border-radius: 10px; margin: 15px 0;'>
|
| 80 |
+
<p style='font-size: 1.2em; font-style: italic;'>"{mission['metin']}"</p>
|
| 81 |
+
<p style='text-align: right; color: #10b981;'>— {mission['kaynak']}</p>
|
| 82 |
+
</div>
|
| 83 |
+
<div style='background: #ffff00; color: #000080; padding: 15px; border-radius: 10px;'>
|
| 84 |
+
<strong>🎯 Bugünün Kalp Görevi:</strong><br>{mission.get('rehber_mesaji', 'Ailenizle vakit geçirin.')}
|
| 85 |
+
</div>
|
| 86 |
+
</div>
|
| 87 |
+
""
|
| 88 |
+
|
| 89 |
+
# --- ADMIN & ANALYTICS FUNCTIONS ---
|
| 90 |
+
def get_admin_content(password):
|
| 91 |
+
if password != "Enes.13112006":
|
| 92 |
+
return gr.update(visible=False), gr.update(visible=False), "### ❌ Hata: Geçersiz Şifre"
|
| 93 |
+
|
| 94 |
+
conn = sqlite3.connect('faithpath.db')
|
| 95 |
+
df = pd.read_sql_query("SELECT * FROM journal_entries ORDER BY id DESC", conn)
|
| 96 |
+
conn.close()
|
| 97 |
+
|
| 98 |
+
if df.empty:
|
| 99 |
+
return gr.update(visible=True), gr.update(visible=False), "### ℹ️ Sistemde henüz veri bulunmuyor."
|
| 100 |
+
|
| 101 |
+
# Analytics
|
| 102 |
+
df['Duygu'] = df['detected_emotion'].str.replace('_', ' ').str.title()
|
| 103 |
+
fig = px.pie(df, names='Duygu', title='Genel Duygu Dağılımı', hole=.3, template='plotly_dark')
|
| 104 |
+
|
| 105 |
+
stats_msg = f"""
|
| 106 |
+
### 📊 Sistem İstatistikleri
|
| 107 |
+
- **Toplam Kayıt:** {len(df)}
|
| 108 |
+
- **En Sık Karşılaşılan:** {df['Duygu'].mode()[0]}
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
return gr.update(visible=True), fig, stats_msg
|
| 112 |
+
|
| 113 |
+
def export_csv(password):
|
| 114 |
+
if password != "Enes.13112006": return None
|
| 115 |
+
conn = sqlite3.connect('faithpath.db')
|
| 116 |
+
df = pd.read_sql_query("SELECT * FROM journal_entries", conn)
|
| 117 |
+
conn.close()
|
| 118 |
+
df.to_csv('faithpath_backup.csv', index=False)
|
| 119 |
+
return 'faithpath_backup.csv'
|
| 120 |
+
|
| 121 |
+
def reset_db(password):
|
| 122 |
+
if password != "Enes.13112006": return "❌ Yetkisiz işlem!"
|
| 123 |
+
conn = sqlite3.connect('faithpath.db')
|
| 124 |
+
conn.execute("DELETE FROM journal_entries")
|
| 125 |
+
conn.commit()
|
| 126 |
+
conn.close()
|
| 127 |
+
return "✅ Veritabanı başarıyla sıfırlandı."
|
| 128 |
+
|
| 129 |
+
# --- GRADIO UI ---
|
| 130 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {{background-color: #0f172a}}") as demo:
|
| 131 |
+
gr.Markdown("# 🕊️ FaithPath Professional v5.8")
|
| 132 |
+
|
| 133 |
+
with gr.Tabs():
|
| 134 |
+
with gr.Tab("🏠 Asistan"):
|
| 135 |
+
txt_input = gr.Textbox(label="Bugün ailenizle ilgili neler yaşadınız?", lines=6)
|
| 136 |
+
submit_btn = gr.Button("Analiz Et", variant="primary")
|
| 137 |
+
html_out = gr.HTML()
|
| 138 |
+
submit_btn.click(process_entry_user, txt_input, html_out)
|
| 139 |
+
|
| 140 |
+
with gr.Tab("🔐 Admin & Analiz"):
|
| 141 |
+
gr.Markdown("### Yönetici Paneli (Şifre Gerekli)")
|
| 142 |
+
with gr.Row():
|
| 143 |
+
admin_pwd = gr.Textbox(label="Admin Şifresi", type="password")
|
| 144 |
+
login_btn = gr.Button("Sisteme Giriş Yap")
|
| 145 |
+
|
| 146 |
+
stats_area = gr.Markdown()
|
| 147 |
+
|
| 148 |
+
with gr.Row(visible=False) as admin_protected_zone:
|
| 149 |
+
with gr.Column():
|
| 150 |
+
plot_area = gr.Plot()
|
| 151 |
+
with gr.Column():
|
| 152 |
+
gr.Markdown("### 🛠️ Veri İşlemleri")
|
| 153 |
+
export_btn = gr.Button("📥 Verileri CSV Olarak İndir")
|
| 154 |
+
export_file = gr.File(label="İndirme Dosyası")
|
| 155 |
+
gr.Markdown("---")
|
| 156 |
+
reset_btn = gr.Button("⚠️ Veritabanını Sıfırla (Geri Dönülemez)", variant="stop")
|
| 157 |
+
reset_status = gr.Markdown()
|
| 158 |
+
|
| 159 |
+
login_btn.click(get_admin_content, admin_pwd, [admin_protected_zone, plot_area, stats_area])
|
| 160 |
+
export_btn.click(export_csv, admin_pwd, export_file)
|
| 161 |
+
reset_btn.click(reset_db, admin_pwd, reset_status)
|
| 162 |
+
|
| 163 |
+
gr.Markdown("---")
|
| 164 |
+
gr.Markdown("<center>Enes YILMAZ - Karabük University | Protected Admin & Dashboard v5.8</center>")
|
| 165 |
+
|
| 166 |
+
demo.launch()
|