AugustinHuang commited on
Commit
0d9bba4
·
verified ·
1 Parent(s): 1feb7c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -145
app.py CHANGED
@@ -2,79 +2,53 @@ import gradio as gr
2
  import plotly.express as px
3
  import plotly.graph_objects as go
4
  import re
5
- from collections import Counter
 
6
 
7
  class TaskDashboardAI_Vietnamese:
8
- def __init__(self):
9
- # BO HẾT TRANSFORMER - CHẠY NHẸ NHÀNG, CHUẨN 100%
 
10
 
11
  self.categories = [
12
  "Learning", "Practice", "Planning",
13
- "Organization", "Research", "Reflection"
14
  ]
15
 
16
- # --- LUẬT QUÉT TỪ TRÁI SANG PHẢI ---
17
- # Sử dụng Regex: \s* giúp bắt cả trường hợp viết dính "tòmò" hoặc có khoảng trắng "tò mò"
18
- # Ưu tiên tuyệt đối: Đi theo thứ tự từ trên xuống dưới. Gặp cái nào trước, chốt cái đó ngay.
19
- self.scan_rules = [
20
- # 1. Learning
21
- (r'tò\s*mò', "Learning"),
22
- (r'hiểu\s*ra', "Learning"),
23
- (r'nắm\s*được', "Learning"),
24
- (r'biết\s*thêm', "Learning"),
25
- (r'học\s*được', "Learning"),
26
- (r'khám\s*phá', "Learning"),
27
- (r'xem\s*video', "Learning"),
28
- (r'đọc\s*sách', "Learning"),
29
- (r'lý\s*thuyết', "Learning"),
30
- (r'học', "Learning"), # Đặt chung chung ở dưới cùng của nhóm
31
-
32
- # 2. Practice
33
- (r'viết\s*code', "Practice"),
34
- (r'thực\s*hành', "Practice"),
35
- (r'fix\s*bug', "Practice"),
36
- (r'thực\s*hành', "Practice"),
37
- (r'làm\s*bài\s*tập', "Practice"),
38
- (r'nghịch\s*code', "Practice"),
39
- (r'code', "Practice"),
40
- (r'implement', "Practice"),
41
- (r'chạy\s*thử', "Practice"),
42
-
43
- # 3. Planning
44
- (r'lên\s*kế\s*hoạch', "Planning"),
45
- (r'lập\s*plan', "Planning"),
46
- (r'đặt\s*mục\s*tiêu', "Planning"),
47
- (r'roadmap', "Planning"),
48
- (r'chiến\s*lược', "Planning"),
49
- (r'dự\s*định', "Planning"),
50
-
51
- # 4. Organization
52
- (r'dọn\s*dẹp', "Organization"),
53
- (r'sắp\s*xếp\s*folder', "Organization"),
54
- (r'tổ\s*chức\s*file', "Organization"),
55
- (r'setup\s*máy', "Organization"),
56
- (r'cấu\s*trúc\s*lại', "Organization"),
57
- (r'tạo\s*folder', "Organization"),
58
-
59
- # 5. Research
60
- (r'research', "Research"),
61
- (r'khảo\s*sát', "Research"),
62
- (r'quan\s*sát', "Research"),
63
- (r'phân\s*tích\s*sâu', "Research"),
64
- (r'so\s*sánh\s*giải\s*pháp', "Research"),
65
- (r'tìm\s*hiểu\s*kỹ', "Research"),
66
- (r'tìm\s*hiểu', "Research"),
67
- (r'tìm\s*kiếm', "Research"),
68
-
69
- # 6. Reflection
70
- (r'nhận\s*ra', "Reflection"),
71
- (r'ý\s*thức\s*được', "Reflection"),
72
- (r'reflect', "Reflection"),
73
- (r'đánh\s*giá\s*bản\s*thân', "Reflection"),
74
- (r'journaling', "Reflection"),
75
- (r'viết\s*nhật\s*ký', "Reflection"),
76
- (r'suy\s*nghĩ', "Reflection"),
77
- ]
78
 
79
  def clean_text(self, text):
80
  return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip()
@@ -88,141 +62,166 @@ class TaskDashboardAI_Vietnamese:
88
  tasks.append(cleaned)
89
  return tasks
90
 
91
- def classify_task(self, task):
92
- """
93
- Logic quét mới: Dùng Regex quét từ trái qua phải.
94
- Gặp pattern đầu tiên khớp -> Trả về ngay lập tức (Early Return).
95
- """
96
- task_lower = task.lower()
97
 
98
- for pattern, category in self.scan_rules:
99
- # re.search sẽ tự động quét từ trái sang phải đến khi tìm thấy
100
- if re.search(pattern, task_lower):
101
- return category
102
-
103
- return "Other"
 
 
 
 
 
 
 
 
104
 
105
- def create_donut_chart(self, cat_counts):
106
- if not cat_counts:
107
  fig = go.Figure()
108
  fig.add_annotation(text="No data", showarrow=False)
109
  return fig
110
 
111
- labels = list(cat_counts.keys())
112
- values = list(cat_counts.values())
113
  colors = px.colors.qualitative.Pastel
114
 
115
  fig = go.Figure(data=[go.Pie(
116
- labels=labels,
117
- values=values,
118
- hole=0.4,
119
- marker_colors=colors,
120
- textinfo='percent+label',
121
  insidetextorientation='radial'
122
  )])
123
 
124
  fig.update_layout(
125
- title={
126
- 'text': "📊 Daily Activity Distribution",
127
- 'y': 0.95, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top'
128
- },
129
- height=450,
130
- showlegend=True,
131
- legend=dict(
132
- orientation="h",
133
- yanchor="bottom",
134
- y=-0.1,
135
- xanchor="center",
136
- x=0.5
137
- ),
138
- margin=dict(t=60, b=60, l=20, r=20)
139
  )
140
  return fig
141
 
142
- def process(self, text):
 
 
143
  if not text or not text.strip():
144
- return None, "⚠️ Please enter some text first."
 
 
 
145
 
146
  tasks = self.extract_tasks(text)
147
  if not tasks:
148
- return None, "❌ No valid tasks found."
149
 
150
- results = []
151
- cat_counter = Counter()
 
 
 
152
 
153
- for task in tasks:
154
- category = self.classify_task(task)
155
- results.append((task, category))
156
- cat_counter[category] += 1
 
 
 
 
 
157
 
158
- chart = self.create_donut_chart(dict(cat_counter))
159
 
160
- # HTML Output đẹp hơn
161
- summary_html = "<div style='font-family: sans-serif;'>"
162
- summary_html += "<h3 style='border-bottom: 2px solid #eee; padding-bottom: 10px;'>📋 Detailed Classification</h3>"
163
- summary_html += "<ul style='list-style-type:none; padding:0;'>"
164
-
165
  color_map = {
166
  "Learning": "#a6cee3", "Practice": "#fb9a99", "Planning": "#b2df8a",
167
  "Organization": "#fdbf6f", "Research": "#cab2d6", "Reflection": "#ffff99", "Other": "#cccccc"
168
  }
169
 
 
 
170
  for task, cat in results:
171
  bg_color = color_map.get(cat, "#eeeeee")
172
- summary_html += f"""
173
- <li style="margin-bottom: 8px; padding: 10px; background-color: #fff; border-left: 5px solid {bg_color}; box-shadow: 0 1px 2px rgba(0,0,0,0.05);">
174
- <span style="font-weight:bold; color:#555; font-size: 0.85em; text-transform:uppercase;">[{cat}]</span>
175
  <span style="color:#333; margin-left: 8px;">{task}</span>
176
  </li>"""
177
- summary_html += "</ul>"
178
 
179
- summary_html += "<h3 style='border-bottom: 2px solid #eee; padding-bottom: 10px; margin-top: 20px;'>📈 Summary</h3><ul>"
180
- total = sum(cat_counter.values())
181
- for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
182
- pct = (count / total) * 100
183
- summary_html += f"<li style='padding: 5px 0;'><b>{cat}</b>: {count} tasks ({pct:.1f}%)</li>"
184
- summary_html += "</ul></div>"
185
-
186
- return chart, summary_html
 
 
 
 
 
 
187
 
188
- # Initialize Agent
189
- ai_agent = TaskDashboardAI_Vietnamese()
190
 
191
- with gr.Blocks(title="Task Dashboard AI", theme=gr.themes.Soft()) as demo:
 
 
 
192
  gr.Markdown("""
193
- # 🇻🇳 Smart Task Dashboard (Rule-Based Regex Engine)
194
- Không dùng AI nặng nề, quét keyword từ trái sang phải - Nhanh, gọn, chính xác theo ý bạn.
195
  """)
196
 
 
 
 
 
197
  with gr.Row():
 
198
  with gr.Column(scale=1):
199
  input_text = gr.Textbox(
200
  label="📝 Nhập hoạt động hàng ngày",
201
  placeholder="Ví dụ:\n• tôi tò mò về cách hoạt động của AI\n• tôi code thử một trang web\n• tôi lên kế hoạch cho tuần sau...",
202
- lines=15
203
  )
204
- btn = gr.Button("🚀 Phân tích", variant="primary", size="lg")
205
 
206
  gr.Examples(
207
  examples=[
208
- """• tôi tò mò về cách hoạt động của neural network
209
- • tôi nghịch code Python suốt buổi sáng
210
- • tôi lên kế hoạch đi du lịch Đà Lạt
211
- • tôi dọn dẹp lại đống file trên desktop
212
- • tôi research về thị trường chứng khoán
213
- • tôi nhận ra mình cần nghỉ ngơi nhiều hơn""",
214
  ],
215
  inputs=input_text
216
  )
217
 
 
218
  with gr.Column(scale=2):
 
219
  chart_output = gr.Plot(label="📊 Biểu đồ phân bổ")
220
- summary_output = gr.HTML(label="📋 Kết quả chi tiết")
 
 
 
 
 
 
 
221
 
 
222
  btn.click(
223
- fn=ai_agent.process,
224
- inputs=input_text,
225
- outputs=[chart_output, summary_output]
226
  )
227
 
228
  demo.launch()
 
2
  import plotly.express as px
3
  import plotly.graph_objects as go
4
  import re
5
+ import json
6
+ from groq import Groq
7
 
8
  class TaskDashboardAI_Vietnamese:
9
+ def __init__(self, groq_api_key):
10
+ self.client = Groq(api_key=groq_api_key)
11
+ self.model = "llama-3.1-8b-instant" # Dùng Llama 3.1 8B cho nhanh và chuẩn
12
 
13
  self.categories = [
14
  "Learning", "Practice", "Planning",
15
+ "Organization", "Research", "Reflection", "Other"
16
  ]
17
 
18
+ # ==========================================
19
+ # PHẦN SYSTEM PROMPT - ÔNG ĐỌC VÀ CLARIFY GIÙM TÔI NHÉ
20
+ # ==========================================
21
+ self.system_prompt = """
22
+ Bạn là một trợ lý AI phân tích hành vi và cảm xúc từ các nhật ký hoạt động hàng ngày của người dùng (bằng tiếng Việt).
23
+ Nhiệm vụ của bạn là đọc danh sách các câu, phân loại từng câu vào ĐÚNG 1 category, và đồng thời phân tích tổng thể cảm xúc của toàn bộ đoạn văn.
24
+
25
+ 1. QUY TẮC PHÂN LOẠI (Categorization):
26
+ - Learning: Học hỏi lý thuyết, xem video, đọc sách, tìm hiểu kiến thức mới, sự tò mò.
27
+ - Practice: Thực hành, viết code, debug, làm bài tập, cài đặt phần mềm, thao tác tay.
28
+ - Planning: Lên kế hoạch, đặt mục tiêu, dự định tương lai, lên roadmap.
29
+ - Organization: Sắp xếp, dọn dẹp file/folder/máy tính, tổ chức lại cấu trúc.
30
+ - Research: Nghiên cứu chuyên sâu, phân tích so sánh, khảo sát thị trường, tìm hiểu kỹ lưỡng.
31
+ - Reflection: Nhìn nhận lại bản thân, đánh giá, suy nghĩ sâu sắc, viết nhật ký cảm xúc.
32
+ - Other: Các hoạt động không thuộc nhóm nào trên (ví dụ: đi ăn, ngủ, giao tiếp hàng ngày).
33
+
34
+ 2. QUY TẮC PHÂN TÍCH CẢM XÚC (Emotion Analysis):
35
+ - Hãy xem xét toàn bộ đoạn văn để xác định cảm xúc chủ đạo.
36
+ - Các cảm xúc có thể là: "Tích cực/Vui vẻ", "Lo lắng/Ap lực", "Tập trung/Lý trí", "Mệt mỏi", "Hào hứng", v.v.
37
+ - Hãy giải thích ngắn gọn TẠI SAO lại có cảm xúc đó dựa trên các từ khóa trong văn bản.
38
+
39
+ 3. ĐỊNH DẠNG ĐẦU RA BẮT BUỘC (JSON):
40
+ Bạn PHẢI trả về chuỗi JSON hợp lệ, không thêm text hay markdown bao quanh. Định dạng như sau:
41
+ {
42
+ "tasks": [
43
+ {"task": "nội dung câu gốc", "category": "Tên Category"},
44
+ {"task": "nội dung câu gốc", "category": "Tên Category"}
45
+ ],
46
+ "emotion": {
47
+ "label": "Tên cảm xúc chủ đạo",
48
+ "reason": "Câu giải thích ngắn gọn tại sao"
49
+ }
50
+ }
51
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def clean_text(self, text):
54
  return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip()
 
62
  tasks.append(cleaned)
63
  return tasks
64
 
65
+ def analyze_with_llm(self, tasks):
66
+ """Gọi Groq API 1 lần duy nhất để lấy cả Category và Emotion"""
67
+ user_prompt = "Hãy phân tích các hoạt động sau:\n" + "\n".join([f"- {t}" for t in tasks])
 
 
 
68
 
69
+ try:
70
+ chat_completion = self.client.chat.completions.create(
71
+ messages=[
72
+ {"role": "system", "content": self.system_prompt},
73
+ {"role": "user", "content": user_prompt}
74
+ ],
75
+ model=self.model,
76
+ temperature=0.1, # Để kết quả phân loại ổn định, ít bị ảo
77
+ response_format={"type": "json_object"} # Ép trả về JSON chuẩn
78
+ )
79
+ return json.loads(chat_completion.choices[0].message.content)
80
+ except Exception as e:
81
+ print(f"Lỗi API: {e}")
82
+ return None
83
 
84
+ def create_donut_chart(self, cat_counter):
85
+ if not cat_counter:
86
  fig = go.Figure()
87
  fig.add_annotation(text="No data", showarrow=False)
88
  return fig
89
 
90
+ labels = list(cat_counter.keys())
91
+ values = list(cat_counter.values())
92
  colors = px.colors.qualitative.Pastel
93
 
94
  fig = go.Figure(data=[go.Pie(
95
+ labels=labels, values=values, hole=0.5,
96
+ marker_colors=colors, textinfo='percent+label',
 
 
 
97
  insidetextorientation='radial'
98
  )])
99
 
100
  fig.update_layout(
101
+ title={'text': "📊 Activity Distribution", 'y': 0.95, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top'},
102
+ height=400, showlegend=True,
103
+ legend=dict(orientation="h", yanchor="bottom", y=-0.1, xanchor="center", x=0.5),
104
+ margin=dict(t=50, b=50, l=20, r=20)
 
 
 
 
 
 
 
 
 
 
105
  )
106
  return fig
107
 
108
+ def process(self, text, api_key):
109
+ if not api_key or not api_key.strip():
110
+ return None, "⚠️ Vui lòng nhập Groq API Key.", ""
111
  if not text or not text.strip():
112
+ return None, "⚠️ Vui lòng nhập hoạt động.", ""
113
+
114
+ # Cập nhật API Key nếu người dùng nhập mới
115
+ self.client = Groq(api_key=api_key)
116
 
117
  tasks = self.extract_tasks(text)
118
  if not tasks:
119
+ return None, "❌ Không tìm thấy task hợp lệ.", ""
120
 
121
+ # Gọi LLM
122
+ llm_result = self.analyze_with_llm(tasks)
123
+
124
+ if not llm_result or "tasks" not in llm_result:
125
+ return None, "❌ Lỗi khi gọi Llama 3. Kiểm tra lại API Key hoặc thử lại.", ""
126
 
127
+ # Xử lý dữ liệu trả về
128
+ results = []
129
+ cat_counter = {}
130
+ for item in llm_result["tasks"]:
131
+ task_text = item.get("task", "")
132
+ category = item.get("category", "Other")
133
+ if category not in self.categories: category = "Other"
134
+ results.append((task_text, category))
135
+ cat_counter[category] = cat_counter.get(category, 0) + 1
136
 
137
+ chart = self.create_donut_chart(cat_counter)
138
 
139
+ # 1. Tạo HTML Detailed Classification (Phần dưới Donut)
 
 
 
 
140
  color_map = {
141
  "Learning": "#a6cee3", "Practice": "#fb9a99", "Planning": "#b2df8a",
142
  "Organization": "#fdbf6f", "Research": "#cab2d6", "Reflection": "#ffff99", "Other": "#cccccc"
143
  }
144
 
145
+ detail_html = "<div style='max-height: 300px; overflow-y: auto; font-family: sans-serif;'>"
146
+ detail_html += "<ul style='list-style-type:none; padding:0;'>"
147
  for task, cat in results:
148
  bg_color = color_map.get(cat, "#eeeeee")
149
+ detail_html += f"""
150
+ <li style="margin-bottom: 6px; padding: 8px; background-color: #fff; border-left: 5px solid {bg_color}; box-shadow: 0 1px 2px rgba(0,0,0,0.05); border-radius: 4px;">
151
+ <span style="font-weight:bold; color:#555; font-size: 0.8em; text-transform:uppercase;">[{cat}]</span>
152
  <span style="color:#333; margin-left: 8px;">{task}</span>
153
  </li>"""
154
+ detail_html += "</ul></div>"
155
 
156
+ # 2. Tạo HTML Emotion Analysis (Phần bên phải)
157
+ emotion_data = llm_result.get("emotion", {})
158
+ emotion_label = emotion_data.get("label", "Không xác định")
159
+ emotion_reason = emotion_data.get("reason", "Không có giải thích")
160
+
161
+ emotion_html = f"""
162
+ <div style="font-family: sans-serif; padding: 15px; background: linear-gradient(135deg, #fdfbfb 0%, #ebedee 100%); border-radius: 10px; height: 100%; box-sizing: border-box;">
163
+ <h3 style="margin-top:0; color:#333;">🧠 Phân tích cảm xúc</h3>
164
+ <div style="background: white; padding: 15px; border-radius: 8px; text-align: center; margin-bottom: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
165
+ <span style="font-size: 1.5em; font-weight: bold; color: #e67e22;">"{emotion_label}"</span>
166
+ </div>
167
+ <p style="color:#555; line-height: 1.6;"><b>💬 Giải thích:</b><br>{emotion_reason}</p>
168
+ </div>
169
+ """
170
 
171
+ return chart, detail_html, emotion_html
 
172
 
173
+ # ==========================================
174
+ # GIAO DIỆN GRADIO ( Layout theo yêu cầu )
175
+ # ==========================================
176
+ with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
177
  gr.Markdown("""
178
+ # 🇻🇳 Smart Task Dashboard (Powered by Llama 3 on Groq)
179
+ Sử dụng LLM để phân loại chính xác và hiểu được ngữ cảnh, cảm xúc của bạn.
180
  """)
181
 
182
+ # Ô nhập API Key nằm ẩn gọn trên cùng
183
+ api_key_input = gr.Textbox(label="🔑 Groq API Key", placeholder="Gõ Groq API Key của bạn vào đây...", type="password")
184
+
185
+ # LAYOUT CHÍNH
186
  with gr.Row():
187
+ # CỘT TRÁI: Nhập liệu
188
  with gr.Column(scale=1):
189
  input_text = gr.Textbox(
190
  label="📝 Nhập hoạt động hàng ngày",
191
  placeholder="Ví dụ:\n• tôi tò mò về cách hoạt động của AI\n• tôi code thử một trang web\n• tôi lên kế hoạch cho tuần sau...",
192
+ lines=20
193
  )
194
+ btn = gr.Button("🚀 Phân tích bằng Llama 3", variant="primary", size="lg")
195
 
196
  gr.Examples(
197
  examples=[
198
+ """• Hôm nay tôi tò mò về cách hoạt động của neural network nên đã xem mấy video explainer
199
+ • Buổi sáng tôi nghịch code Python làm cái web scraper, bị bug mất 2 tiếng mới fix được
200
+ • Tôi nhận ra mình quản lý thời gian quá kém, dạo này hay bị lẩn thẩn
201
+ • Chiều tôi dọn dẹp lại toàn bộ folder trên Desktop cho dễ tìm
202
+ • Tối tôi lên kế hoạch chi tiết cho dự án sắp tới""",
 
203
  ],
204
  inputs=input_text
205
  )
206
 
207
+ # CỘT PHẢI: Chia làm 2 hàng ngang
208
  with gr.Column(scale=2):
209
+ # HÀNG 1: Biểu đồ Donut (chiếm toàn bộ ngang)
210
  chart_output = gr.Plot(label="📊 Biểu đồ phân bổ")
211
+
212
+ # HÀNG 2: Chia làm 2 cột nhỏ (Detailed bên trái, Emotion bên phải)
213
+ with gr.Row():
214
+ with gr.Column(scale=1):
215
+ detail_output = gr.HTML(label="📋 Detailed Classification")
216
+
217
+ with gr.Column(scale=1):
218
+ emotion_output = gr.HTML(label="💡 Cảm xúc")
219
 
220
+ # Sự kiện bấm nút
221
  btn.click(
222
+ fn=TaskDashboardAI_Vietnamese(api_key="temp").process,
223
+ inputs=[input_text, api_key_input],
224
+ outputs=[chart_output, detail_output, emotion_output]
225
  )
226
 
227
  demo.launch()