adikwok commited on
Commit
3987ed8
ยท
verified ยท
1 Parent(s): f4038dd

ultra-light-advance

Browse files
Files changed (1) hide show
  1. app.py +165 -0
app.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ import json
5
+ from datetime import datetime
6
+ import re
7
+ from pathlib import Path
8
+ import uuid
9
+
10
+ # === CONFIG ===
11
+ STORAGE_DIR = Path("journal_data")
12
+ STORAGE_DIR.mkdir(exist_ok=True)
13
+ HISTORY_FILE = STORAGE_DIR / "history.json"
14
+ API_KEY = os.getenv("GROQ_API_KEY")
15
+ API_URL = "https://api.groq.com/openai/v1/chat/completions"
16
+ MODEL = "gemma2-9b-it"
17
+
18
+ # === MEMORY: Load history ===
19
+ def load_history():
20
+ if HISTORY_FILE.exists():
21
+ try:
22
+ with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
23
+ return json.load(f)
24
+ except: pass
25
+ return []
26
+
27
+ def save_history(history):
28
+ with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
29
+ json.dump(history[-100:], f, indent=2, ensure_ascii=False) # Simpen 100 terakhir
30
+
31
+ chat_history = load_history()
32
+ current_session = str(uuid.uuid4())
33
+
34
+ # === Smart Summary Generator ===
35
+ def generate_summary(messages):
36
+ if not messages:
37
+ return "User baru mulai ngobrol."
38
+
39
+ user_msgs = [m for m in messages if m['role'] == 'user']
40
+ topics = [m['topic'] for m in user_msgs[-5:]]
41
+ main_topic = max(set(topics), key=topics.count) if topics else "general"
42
+
43
+ # Emosi kasar
44
+ pos = sum(1 for m in user_msgs[-3:] if any(w in m['content'].lower() for w in ['senang', 'semangat', 'baik']))
45
+ neg = sum(1 for m in user_msgs[-3:] if any(w in m['content'].lower() for w in ['capek', 'sedih', 'gagal']))
46
+ mood = "positif" if pos > neg else "negatif" if neg > pos else "netral"
47
+
48
+ # Gaya bicara
49
+ style = "kasual" if any('gue' in m['content'].lower() or 'anjir' in m['content'].lower() for m in user_msgs[-2:]) else "formal"
50
+
51
+ return f"""
52
+ Topik utama: {main_topic}
53
+ Mood: {mood}
54
+ Gaya: {style}
55
+ Catatan: Validasi emosi dulu, hindari klise, akhiri dengan pertanyaan terbuka.
56
+ """.strip()
57
+
58
+ # === Deteksi Gaya Khusus (Tom Schreiter, dll) ===
59
+ def detect_style_instruction(content):
60
+ content = content.lower()
61
+ if "gaya schreiter" in content: return "Tom Schreiter: pendek, ngena, Mini-Stories, empati, efektif."
62
+ if "gaya henneke" in content: return "Henneke Duistermaat: hangat, relatable, humor halus."
63
+ if "gaya ogilvy" in content: return "David Ogilvy: elegan, persuasive, storytelling memikat."
64
+ if "gaya halbert" in content: return "Gary Halbert: bold, direct, seperti surat penjualan."
65
+ if "gaya rohn" in content: return "Jim Rohn: inspiratif, penuh wisdom."
66
+ if "gaya lao tzu" in content: return "Lao Tzu: filosofis, minimalis, tenang."
67
+ return "santai, cerdas, kayak ngobrol sama world-class mentor."
68
+
69
+ # === Kirim ke Groq + Context Ringan ===
70
+ def groq_respond(message, topic):
71
+ if not message.strip(): return "โŒ Isi pesannya dulu.", ""
72
+ if not API_KEY: return "โŒ GROQ_API_KEY belum diset.", ""
73
+
74
+ global chat_history, current_session
75
+
76
+ # Simpan user message
77
+ user_msg = {
78
+ "role": "user",
79
+ "content": message.strip(),
80
+ "topic": topic,
81
+ "timestamp": datetime.now().isoformat(),
82
+ "session_id": current_session
83
+ }
84
+ chat_history.append(user_msg)
85
+
86
+ # Buat context: system + summary + 2 terakhir
87
+ summary = generate_summary(chat_history)
88
+ style_instruction = detect_style_instruction(message)
89
+
90
+ recent = chat_history[-2:] # Cuma 2 terakhir
91
+ messages = [
92
+ {
93
+ "role": "system",
94
+ "content": f"""Kamu adalah Deepseek-Mentor.
95
+ Prinsip:
96
+ 1. Validasi emosi dulu sebelum solusi.
97
+ 2. Hindari jawaban generik โ€” tanya balik yang mendalam.
98
+ 3. Sesuaikan gaya: {style_instruction}
99
+ 4. Akhiri dengan pertanyaan terbuka yang mengajak bertindak.
100
+ 5. Jangan jadi motivator klise. Jadi teman yang kompeten.
101
+
102
+ [MEMORY]
103
+ {summary}
104
+ """.strip()
105
+ }
106
+ ] + [{"role": m["role"], "content": m["content"]} for m in recent]
107
+
108
+ try:
109
+ resp = requests.post(
110
+ API_URL,
111
+ headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
112
+ json={
113
+ "model": MODEL,
114
+ "messages": messages,
115
+ "max_tokens": 1024,
116
+ "temperature": 0.9,
117
+ "top_p": 0.95,
118
+ "presence_penalty": 0.8,
119
+ "frequency_penalty": 0.7
120
+ },
121
+ timeout=30
122
+ )
123
+ resp.raise_for_status()
124
+ ai_msg = resp.json()["choices"][0]["message"]["content"]
125
+
126
+ # Simpan response
127
+ chat_history.append({
128
+ "role": "assistant",
129
+ "content": ai_msg,
130
+ "topic": topic,
131
+ "timestamp": datetime.now().isoformat(),
132
+ "session_id": current_session
133
+ })
134
+ save_history(chat_history)
135
+ return ai_msg, ""
136
+ except Exception as e:
137
+ return f"โŒ Error: {str(e)}", ""
138
+
139
+ # === Gradio UI ===
140
+ with gr.Blocks(title="๐Ÿง  AI Journal Paling Keren Sedunia", theme=gr.themes.Soft()) as demo:
141
+ gr.Markdown("# ๐Ÿง  AI Journal Paling Keren Sedunia")
142
+ gr.Markdown("Minimalis. Pintar. Nyambung. Input token < 300, tapi tetap kayak ngobrol beneran.")
143
+
144
+ with gr.Tab("๐Ÿ’ฌ Chat"):
145
+ response = gr.Textbox(label="๐Ÿค– AI", lines=10, interactive=False, show_copy_button=True)
146
+ user_input = gr.Textbox(label="โœ๏ธ Kamu", placeholder="Apa yang kamu rasakan sekarang?", lines=3)
147
+ topic_input = gr.Textbox(label="๐Ÿท๏ธ Topik", value="journal", placeholder="e.g., produktivitas, hubungan")
148
+ send_btn = gr.Button("๐Ÿš€ Kirim")
149
+
150
+ with gr.Tab("๐Ÿ“š Riwayat"):
151
+ history_display = gr.Textbox(label="Riwayat", lines=15, interactive=False, show_copy_button=True)
152
+ refresh_btn = gr.Button("๐Ÿ”„ Muat Ulang")
153
+
154
+ with gr.Tab("๐Ÿ“Š Ringkasan"):
155
+ summary_display = gr.Textbox(label="Insight", lines=10, interactive=False)
156
+ gen_summary_btn = gr.Button("๐Ÿ”ฎ Buat Ringkasan")
157
+
158
+ # Actions
159
+ send_btn.click(groq_respond, [user_input, topic_input], [response, user_input])
160
+ refresh_btn.click(lambda: "\n\n".join(f"[{m['timestamp'][:10]}] {m['role']}: {m['content']}" for m in chat_history[-20:]), None, history_display)
161
+ gen_summary_btn.click(lambda: generate_summary(chat_history), None, summary_display)
162
+
163
+ # Jalanin
164
+ if __name__ == "__main__":
165
+ demo.launch()