AugustinHuang commited on
Commit
ad43df0
·
verified ·
1 Parent(s): 1cdf586

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +323 -0
app.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import plotly.graph_objects as go
3
+ import plotly.express as px
4
+ import re
5
+ import json
6
+ from collections import Counter
7
+
8
+ # Kiểm tra thư viện Groq
9
+ try:
10
+ from groq import Groq
11
+ GROQ_AVAILABLE = True
12
+ except ImportError:
13
+ GROQ_AVAILABLE = False
14
+
15
+ class SmartJournalAI:
16
+ def __init__(self):
17
+ # Các category cơ bản để fallback hoặc hiển thị
18
+ self.categories = [
19
+ "Learning 📚",
20
+ "Practice 💻",
21
+ "Planning 🗺️",
22
+ "Organization 📂",
23
+ "Research 🔍",
24
+ "Reflection 🧘"
25
+ ]
26
+
27
+ # Từ khóa hỗ trợ phân loại offline (nếu không có API key)
28
+ self.priority_keywords = {
29
+ "Learning 📚": { "strong": ["tò mò", "hiểu ra", "nắm được", "biết thêm", "học được", "khám phá", "learn", "understand", "study"],
30
+ "common": ["học", "xem video", "đọc sách", "tutorial", "lý thuyết", "course"]},
31
+ "Practice 💻": { "strong": ["code", "viết code", "debug", "fix bug", "thực hành", "làm bài tập", "nghịch code", "build", "implement"],
32
+ "common": ["làm", "thử", "xây dựng", "chạy thử", "practice", "coding"]},
33
+ "Planning 🗺️": { "strong": ["lên kế hoạch", "lập plan", "đặt mục tiêu", "roadmap", "chiến lược", "plan", "goal"],
34
+ "common": ["muốn", "sẽ", "dự định", "target", "mong muốn", "schedule"]},
35
+ "Organization 📂": { "strong": ["dọn dẹp", "sắp xếp folder", "tổ chức file", "setup máy", "cấu trúc lại", "clean up", "organize"],
36
+ "common": ["lưu", "tạo folder", "quản lý", "gọn gàng", "file management"]},
37
+ "Research 🔍": { "strong": ["research", "khảo sát", "phân tích sâu", "so sánh giải pháp", "tìm hiểu kỹ", "investigate"],
38
+ "common": ["tìm hiểu", "tìm kiếm", "đọc tài liệu", "search", "explore"]},
39
+ "Reflection 🧘": { "strong": ["nhận ra", "ý thức được", "reflect", "đánh giá bản thân", "journaling", "realize", "mindfulness"],
40
+ "common": ["suy nghĩ", "thấy rằng", "cảm thấy", "viết nhật ký", "thoughts"]}
41
+ }
42
+
43
+ def clean_text(self, text):
44
+ """Làm sạch văn bản đầu vào"""
45
+ return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip()
46
+
47
+ def extract_tasks(self, text):
48
+ """Tách các dòng thành task riêng biệt"""
49
+ lines = text.strip().split('\n')
50
+ return [self.clean_text(line) for line in lines if self.clean_text(line) and len(self.clean_text(line)) > 4]
51
+
52
+ def _call_groq_llm(self, prompt, api_key):
53
+ """Gọi API Groq an toàn"""
54
+ if not GROQ_AVAILABLE or not api_key:
55
+ return None
56
+ try:
57
+ client = Groq(api_key=api_key)
58
+ response = client.chat.completions.create(
59
+ model="llama-3.3-70b-versatile",
60
+ messages=[{"role": "user", "content": prompt}],
61
+ temperature=0.3, # Tăng nhẹ độ sáng tạo cho lời khuyên
62
+ max_tokens=800,
63
+ top_p=0.9
64
+ )
65
+ return response.choices[0].message.content
66
+ except Exception as e:
67
+ return f"⚠️ Lỗi kết nối Groq: {str(e)}"
68
+
69
+ def classify_task_offline(self, task):
70
+ """Phân loại cơ bản dựa trên từ khóa (Fallback)"""
71
+ task_lower = task.lower()
72
+
73
+ # 1. Quét Strong Keywords
74
+ for cat, keys in self.priority_keywords.items():
75
+ if any(word in task_lower for word in keys["strong"]):
76
+ return cat
77
+
78
+ # 2. Tính điểm Common Keywords
79
+ scores = {cat: 0 for cat in self.categories}
80
+ found_common = False
81
+ for cat, keys in self.priority_keywords.items():
82
+ for word in keys["common"]:
83
+ if word in task_lower:
84
+ scores[cat] += 1
85
+ found_common = True
86
+
87
+ if found_common and max(scores.values()) >= 1: # Giảm ngưỡng xuống 1 để dễ detect hơn
88
+ return max(scores, key=scores.get)
89
+
90
+ return "Other 📝"
91
+
92
+ def create_donut_chart(self, cat_counts):
93
+ """Tạo biểu đồ Donut nhất quán và đẹp mắt"""
94
+ if not cat_counts:
95
+ fig = go.Figure()
96
+ fig.add_annotation(text="Chưa có dữ liệu hoạt động", showarrow=False, font=dict(size=14))
97
+ fig.update_layout(height=300, margin=dict(t=0, b=0, l=0, r=0))
98
+ return fig
99
+
100
+ labels = list(cat_counts.keys())
101
+ values = list(cat_counts.values())
102
+
103
+ # Màu sắc pastel dịu mắt
104
+ colors = px.colors.qualitative.Pastel
105
+
106
+ fig = go.Figure(data=[go.Pie(
107
+ labels=labels,
108
+ values=values,
109
+ hole=0.4, # Hole lớn hơn cho hiện đại
110
+ marker_colors=colors,
111
+ textinfo='percent+label',
112
+ insidetextorientation='radial',
113
+ textfont=dict(size=10, color="#444"),
114
+ hoverinfo='label+percent+value'
115
+ )])
116
+
117
+ fig.update_layout(
118
+ showlegend=True,
119
+ legend=dict(
120
+ orientation="h", # Legend ngang
121
+ yanchor="bottom",
122
+ y=-0.1, # Đẩy legend xuống dưới chart
123
+ xanchor="center",
124
+ x=0.5,
125
+ font=dict(size=10)
126
+ ),
127
+ margin=dict(t=20, b=60, l=20, r=20), # Chừa chỗ cho legend bên dưới
128
+ height=350,
129
+ font=dict(family="Arial, sans-serif")
130
+ )
131
+ return fig
132
+
133
+ def generate_advice_and_classify(self, tasks, cat_counter, api_key):
134
+ """
135
+ Hàm cốt lõi: Sử dụng LLM để phân loại chính xác VÀ đưa ra lời khuyên an ủi/động viên.
136
+ Trả về: JSON chứa danh sách task đã phân loại + Lời khuyên tổng hợp.
137
+ """
138
+
139
+ # Chuẩn bị dữ liệu thống kê sơ bộ để gửi cho LLM
140
+ stats_summary = ", ".join([f"{cat}: {count}" for cat, count in cat_counter.items()])
141
+ tasks_list_str = "\n".join([f"- {t}" for t in tasks])
142
+
143
+ prompt = f"""
144
+ Bạn là một người bạn đồng hành thông minh, ân cần và sâu sắc. Nhiệm vụ của bạn là phân tích nhật ký hoạt động hàng ngày của người dùng.
145
+
146
+ Dữ liệu đầu vào:
147
+ 1. Danh sách hoạt động:
148
+ {tasks_list_str}
149
+
150
+ 2. Thống kê sơ bộ (dựa trên từ khóa):
151
+ {stats_summary}
152
+
153
+ YÊU CẦU:
154
+ Hãy thực hiện 2 việc sau và trả về duy nhất một chuỗi JSON hợp lệ (không kèm markdown code block):
155
+
156
+ 1. PHÂN LOẠI CHI TIẾT: Xét từng task trong danh sách, gán nó vào một trong các nhóm sau: ["Learning 📚", "Practice 💻", "Planning 🗺️", "Organization 📂", "Research 🔍", "Reflection 🧘", "Other 📝"]. Cố gắng phân loại chính xác nhất có thể.
157
+
158
+ 2. LỜI KHUYÊN & AN ỦI (Advice):
159
+ - Dựa vào sự phân bố hoạt động, hãy đưa ra một lời nhận xét ngắn gọn, ấm áp và mang tính xây dựng.
160
+ - Ví dụ: Nếu người dùng học nhiều nhưng ít thực hành -> Khuyên họ nên thử áp dụng kiến thức vào dự án nhỏ.
161
+ - Ví dụ: Nếu người dùng làm việc quá nhiều -> Khuyên họ nghỉ ngơi.
162
+ - Ví dụ: Nếu người dùng chỉ tổ chức file -> Khen ngợi sự ngăn nắp nhưng gợi ý dành thời gian cho sáng tạo.
163
+ - QUAN TRỌNG: Hãy phát hiện ngôn ngữ mà người dùng sử dụng trong các task (Tiếng Việt, Tiếng Anh, v.v.) và viết lời khuyên bằng CHÍNH NGÔN NGỮ ĐÓ để tạo sự gần gũi.
164
+
165
+ FORMAT JSON TRẢ VỀ:
166
+ {{
167
+ "classified_tasks": [
168
+ {"task": "nội dung task gốc", "category": "Tên Category"}
169
+ ],
170
+ "advice": "Lời khuyên ấm áp, ngắn gọn (khoảng 2-3 câu) bằng ngôn ngữ của người dùng."
171
+ }}
172
+ """
173
+
174
+ res = self._call_groq_llm(prompt, api_key)
175
+
176
+ if not res or res.startswith("⚠️"):
177
+ # Fallback nếu lỗi API
178
+ fallback_results = [{"task": t, "category": self.classify_task_offline(t)} for t in tasks]
179
+ return {
180
+ "classified_tasks": fallback_results,
181
+ "advice": "⚠️ Không thể kết nối AI để đưa ra lời khuyên chi tiết. Nhưng bạn đã làm rất tốt khi ghi chép lại ngày hôm nay!"
182
+ }
183
+
184
+ try:
185
+ # Xử lý trường hợp LLM trả về markdown ```json ... ```
186
+ clean_res = res.replace("```json", "").replace("```", "").strip()
187
+ data = json.loads(clean_res)
188
+ return data
189
+ except Exception as e:
190
+ print(f"JSON Parse Error: {e}")
191
+ # Fallback
192
+ fallback_results = [{"task": t, "category": self.classify_task_offline(t)} for t in tasks]
193
+ return {
194
+ "classified_tasks": fallback_results,
195
+ "advice": "Hệ thống gặp chút trục trặc khi phân tích sâu, nhưng biểu đồ bên dưới vẫn phản ánh đúng nỗ lực của bạn hôm nay."
196
+ }
197
+
198
+ def process(self, text, api_key):
199
+ if not text or not text.strip():
200
+ return None, "⚠️ Vui lòng nhập hoạt động của bạn.", ""
201
+
202
+ tasks = self.extract_tasks(text)
203
+ if not tasks:
204
+ return None, "❌ Không tìm thấy task hợp lệ (cần >4 ký tự).", ""
205
+
206
+ # Bước 1: Đếm sơ bộ để vẽ chart ngay lập tức (hoặc dùng kết quả từ LLM nếu muốn chờ lâu hơn)
207
+ # Ở đây ta sẽ đợi LLM phân loại xong rồi mới vẽ chart để đảm bảo consistency giữa Chart và Advice
208
+ # Tuy nhiên, để UX tốt hơn, ta có thể dùng Offline classification cho Chart, còn LLM cho Advice.
209
+ # Nhưng yêu cầu của bạn là "consistent", nên ta sẽ dùng kết quả từ LLM để vẽ lại chart nếu có API.
210
+
211
+ has_api = bool(api_key and GROQ_AVAILABLE)
212
+
213
+ if has_api:
214
+ ai_result = self.generate_advice_and_classify(tasks, Counter(), api_key)
215
+ classified_tasks = ai_result.get("classified_tasks", [])
216
+ advice_text = ai_result.get("advice", "")
217
+
218
+ # Xây dựng lại Counter từ kết quả AI
219
+ final_counter = Counter([item['category'] for item in classified_tasks])
220
+ else:
221
+ # Chế độ Offline
222
+ classified_tasks = []
223
+ final_counter = Counter()
224
+ for t in tasks:
225
+ cat = self.classify_task_offline(t)
226
+ classified_tasks.append({"task": t, "category": cat})
227
+ final_counter[cat] += 1
228
+ advice_text = "💡 Mẹo: Nhập Groq API Key để nhận lời khuyên cá nhân hóa từ AI Llama-3 nhé!"
229
+
230
+ # Vẽ biểu đồ
231
+ chart = self.create_donut_chart(dict(final_counter))
232
+
233
+ # Tạo HTML chi tiết
234
+ color_map = {
235
+ "Learning 📚": "#a6cee3", "Practice 💻": "#fb9a99", "Planning 🗺️": "#b2df8a",
236
+ "Organization 📂": "#fdbf6f", "Research 🔍": "#cab2d6", "Reflection 🧘": "#ffff99",
237
+ "Other 📝": "#cccccc"
238
+ }
239
+
240
+ html_details = "<div style='font-family:sans-serif; font-size: 0.9em;'>"
241
+ for item in classified_tasks:
242
+ bg = color_map.get(item['category'], "#eee")
243
+ html_details += f'''
244
+ <div style="margin-bottom:8px; padding:10px; background:#fff; border-left:5px solid {bg}; box-shadow:0 1px 3px rgba(0,0,0,0.05); border-radius: 4px;">
245
+ <span style="font-weight:bold; color:#555; font-size:0.85em; text-transform:uppercase;">[{item['category']}]</span>
246
+ <span style="color:#333; margin-left:8px;">{item['task']}</span>
247
+ </div>'''
248
+ html_details += "</div>"
249
+
250
+ return chart, advice_text, html_details
251
+
252
+ # Khởi tạo Agent
253
+ ai_agent = SmartJournalAI()
254
+
255
+ with gr.Blocks(title="Smart Journal AI", theme=gr.themes.Soft()) as demo:
256
+ gr.Markdown("# 🇻🇳 Smart Journal AI\n*Người bạn đồng hành phân tích & an ủi qua nhật ký hàng ngày*")
257
+
258
+ with gr.Row():
259
+ # CỘT TRÁI: INPUT
260
+ with gr.Column(scale=1):
261
+ input_text = gr.Textbox(
262
+ label="📝 Hôm nay bạn đã làm gì?",
263
+ lines=8,
264
+ placeholder="Ví dụ:\n• Tôi tò mò về cách hoạt động của AI\n• Code thử một trang web nhỏ\n• Dọn dẹp desktop cho gọn gàng...",
265
+ elem_id="input_box"
266
+ )
267
+ btn = gr.Button("✨ Phân tích & Nhận lời khuyên", variant="primary", size="lg")
268
+
269
+ gr.Examples(
270
+ examples=[
271
+ "• tôi tò mò về neural network\n• tôi nghịch code Python suốt sáng\n• tôi cảm thấy hơi mệt vì làm việc quá nhiều",
272
+ "• I spent 2 hours reading about quantum physics\n• I organized my photo library\n• I feel confused about my career path",
273
+ "• Lên kế hoạch đi Đà Lạt cuối tuần\n• Research vé máy bay\n• Mua vali mới"
274
+ ],
275
+ inputs=input_text
276
+ )
277
+
278
+ api_key_input = gr.Textbox(
279
+ label="🔑 Groq API Key (Optional)",
280
+ type="password",
281
+ info="Để nhận lời khuyên thông minh từ Llama-3. Key không được lưu trữ."
282
+ )
283
+ gr.Markdown("""
284
+ <small>🔒 <b>Bảo mật:</b> Key chỉ được dùng để gửi request đến Groq và không lưu lại trên server.</small>
285
+ """)
286
+
287
+ # CỘT GIỮA: BIỂU ĐỒ
288
+ with gr.Column(scale=1):
289
+ gr.Markdown("### 📊 Cân bằng cuộc sống")
290
+ chart_output = gr.Plot(label="Phân bổ hoạt động")
291
+
292
+ # CỘT PHẢI: LỜI KHUYÊN & CHI TIẾT
293
+ with gr.Column(scale=1):
294
+ gr.Markdown("### 💬 Lời nhắn từ AI")
295
+ advice_output = gr.Markdown(
296
+ value="_Nhấn nút phân tích để nhận lời khuyên..._",
297
+ elem_classes=["advice-box"]
298
+ )
299
+
300
+ with gr.Accordion("📋 Chi tiết phân loại", open=False):
301
+ summary_output = gr.HTML()
302
+
303
+ # Style tùy chỉnh cho box lời khuyên
304
+ gr.HTML("""
305
+ <style>
306
+ .advice-box {
307
+ background-color: #f0fdf4; /* Màu xanh nhạt dịu mắt */
308
+ border: 1px solid #bbf7d0;
309
+ border-radius: 8px;
310
+ padding: 15px;
311
+ min-height: 100px;
312
+ }
313
+ </style>
314
+ """)
315
+
316
+ btn.click(
317
+ fn=ai_agent.process,
318
+ inputs=[input_text, api_key_input],
319
+ outputs=[chart_output, advice_output, summary_output]
320
+ )
321
+
322
+ if __name__ == "__main__":
323
+ demo.launch(share=False)