AugustinHuang commited on
Commit
516cc59
·
verified ·
1 Parent(s): 2d83483

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -74
app.py CHANGED
@@ -1,14 +1,13 @@
1
  import gradio as gr
2
  import plotly.express as px
3
  import plotly.graph_objects as go
4
- import pandas as pd
5
  import re
6
  from transformers import pipeline
7
  from collections import Counter
8
 
9
  class TaskDashboardAI_Vietnamese:
10
  def __init__(self):
11
- # Khởi tạo Model ML
12
  try:
13
  self.classifier = pipeline(
14
  "zero-shot-classification",
@@ -16,46 +15,46 @@ class TaskDashboardAI_Vietnamese:
16
  device=-1
17
  )
18
  self.use_ml = True
19
- except Exception as e:
20
- print(f"ML Model load failed: {e}")
21
  self.use_ml = False
22
 
23
  self.categories = [
24
  "Learning", "Practice", "Planning",
25
  "Organization", "Research", "Reflection"
26
  ]
27
-
28
- # Keywords cải tiến
29
- self.keywords = {
 
 
30
  "Learning": {
31
- "common": ["học", "xem video", "đọc sách", "tutorial", "course", "khái niệm", "lý thuyết"],
32
- "strong": ["hiểu ra", "nắm bắt", "biết thêm", "learned", "studied"]
33
  },
34
  "Practice": {
35
- "common": ["làm bài tập", "thử", "nghịch", "code", "viết code", "implement", "xây dựng"],
36
- "strong": ["debug", "fix bug", "chạy thử", "error", "sửa lỗi", "coding", "practice"]
37
  },
38
  "Planning": {
39
- "common": ["muốn", "sẽ", "dự định", "lên kế hoạch", "target", "mục tiêu"],
40
- "strong": ["roadmap", "MVP", "quick wins", "chiến lược", "deadline", "schedule"]
41
  },
42
  "Organization": {
43
- "common": ["lưu", "tạo folder", "sắp xếp", "dọn dẹp", "quản lý file"],
44
- "strong": ["directory", "structure", "organize", "setup environment", "config"]
45
  },
46
  "Research": {
47
- "common": ["tìm hiểu", "tìm kiếm", "đọc tài liệu", "search google"],
48
- "strong": ["research", "survey", "phân tích sâu", "so sánh", "investigate", "paper"]
49
  },
50
  "Reflection": {
51
- "common": ["suy nghĩ", "nhận ra", "thấy rằng", "journal", "viết nhật ký"],
52
- "strong": ["reflect", "ý thức", "đánh giá bản thân", "review", "self-aware", "cảm thấy"]
53
  }
54
  }
55
 
56
  def clean_text(self, text):
57
- text = re.sub(r'^[•\-\*\d\.\)]+\s*', '', text)
58
- return text.strip()
59
 
60
  def extract_tasks(self, text):
61
  lines = text.strip().split('\n')
@@ -67,43 +66,68 @@ class TaskDashboardAI_Vietnamese:
67
  return tasks
68
 
69
  def classify_task(self, task):
 
 
 
 
 
 
 
70
  task_lower = task.lower()
71
- scores = {cat: 0 for cat in self.categories}
72
 
73
- for category, keys in self.keywords.items():
74
- for word in keys["common"]:
75
- if word in task_lower:
76
- scores[category] += 1
77
  for word in keys["strong"]:
78
  if word in task_lower:
79
- scores[category] += 3
80
 
81
- max_keyword_score = max(scores.values())
 
 
82
 
83
- if max_keyword_score >= 2:
84
- return max(scores, key=scores.get)
 
 
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  if self.use_ml:
87
  try:
88
  result = self.classifier(
89
  task,
90
  self.categories,
91
  multi_label=False,
92
- hypothesis_template="This daily activity is related to {}."
93
  )
94
- if result['scores'][0] > 0.35:
 
95
  return result['labels'][0]
96
  except:
97
  pass
98
-
99
- best_cat = max(scores, key=scores.get)
100
- return best_cat if max_keyword_score > 0 else "Other"
 
 
 
101
 
102
  def create_donut_chart(self, cat_counts):
103
- """FIXED: Layout điều chỉnh để không bị đè chữ"""
104
  if not cat_counts:
105
  fig = go.Figure()
106
- fig.add_annotation(text="No data to display", showarrow=False, font_size=20)
107
  return fig
108
 
109
  labels = list(cat_counts.keys())
@@ -116,29 +140,24 @@ class TaskDashboardAI_Vietnamese:
116
  hole=0.4,
117
  marker_colors=colors,
118
  textinfo='percent+label',
119
- insidetextorientation='radial',
120
- hovertemplate="<b>%{label}</b><br>Tasks: %{value}<extra></extra>"
121
  )])
122
 
123
- # --- CẤU HÌNH LAYOUT QUAN TRỌNG ---
124
  fig.update_layout(
125
  title={
126
  'text': "📊 Daily Activity Distribution",
127
- 'y': 0.95, # Đẩy title sát mép trên
128
- 'x': 0.5,
129
- 'xanchor': 'center',
130
- 'yanchor': 'top'
131
  },
132
- height=450, # Tăng chiều cao một chút cho thoáng
133
  showlegend=True,
134
  legend=dict(
135
- orientation="h", # Hiển thị ngang
136
- yanchor="bottom", # Neo từ đáy
137
- y=-0.1, # Đẩy legend XUỐNG DƯỚI biểu đồ (âm số)
138
- xanchor="center", # Căn giữa ngang
139
- x=0.5 # Vị trí trung tâm
140
  ),
141
- margin=dict(t=60, b=60, l=20, r=20) # Chừa khoảng trống trên/dưới
142
  )
143
  return fig
144
 
@@ -160,9 +179,9 @@ class TaskDashboardAI_Vietnamese:
160
 
161
  chart = self.create_donut_chart(dict(cat_counter))
162
 
163
- # Tạo báo cáo HTML đẹp hơn
164
  summary_html = "<div style='font-family: sans-serif;'>"
165
- summary_html += "<h3 style='border-bottom: 2px solid #ddd; padding-bottom: 10px;'>📋 Detailed Classification</h3>"
166
  summary_html += "<ul style='list-style-type:none; padding:0;'>"
167
 
168
  color_map = {
@@ -173,13 +192,13 @@ class TaskDashboardAI_Vietnamese:
173
  for task, cat in results:
174
  bg_color = color_map.get(cat, "#eeeeee")
175
  summary_html += f"""
176
- <li style="margin-bottom: 8px; padding: 10px; background-color: #fff; border-left: 5px solid {bg_color}; box-shadow: 0 1px 3px rgba(0,0,0,0.1); border-radius: 4px;">
177
- <span style="font-weight:bold; color:#555; font-size: 0.9em;">[{cat}]</span>
178
- <span style="color:#333;">{task}</span>
179
  </li>"""
180
  summary_html += "</ul>"
181
 
182
- summary_html += "<h3 style='border-bottom: 2px solid #ddd; padding-bottom: 10px; margin-top: 20px;'>📈 Summary Statistics</h3><ul>"
183
  total = sum(cat_counter.values())
184
  for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
185
  pct = (count / total) * 100
@@ -191,40 +210,36 @@ class TaskDashboardAI_Vietnamese:
191
  # Initialize Agent
192
  ai_agent = TaskDashboardAI_Vietnamese()
193
 
194
- # Gradio UI
195
  with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
196
  gr.Markdown("""
197
- # 🇻🇳 AI Task Dashboard for Vietnamese
198
- Phân tích hoạt động hàng ngày của bạn một cách thông minh.
199
  """)
200
 
201
  with gr.Row():
202
  with gr.Column(scale=1):
203
  input_text = gr.Textbox(
204
- label="📝 Paste your daily notes here",
205
- placeholder="Example:\n• tôi đã học Python\n• fix bug login page...",
206
  lines=15
207
  )
208
- btn = gr.Button("🚀 Analyze & Visualize", variant="primary", size="lg")
209
 
210
  gr.Examples(
211
  examples=[
212
- """• tôi đã nhớ được 1 dạng pattern phần giải thích
213
- • tôi đã ý thức được tầm quan trọng của quick wins
214
- • tôi đã quyết định viết những dòng này
215
- • tôi đã nghịch Python dù chưa biết def()
216
- • tôi đã xem xong 1 video về hàm def()
217
- • tôi đã thực hành web scraping
218
- • tôi đã tìm hiểu về tập đoàn nhà nước
219
- • tôi đã lập ra 2 folders
220
- • tôi đã sửa 1 số bài toán làm sai""",
221
  ],
222
  inputs=input_text
223
  )
224
 
225
  with gr.Column(scale=2):
226
- chart_output = gr.Plot(label="📊 Activity Distribution")
227
- summary_output = gr.HTML(label="📋 Analysis Results")
228
 
229
  btn.click(
230
  fn=ai_agent.process,
 
1
  import gradio as gr
2
  import plotly.express as px
3
  import plotly.graph_objects as go
 
4
  import re
5
  from transformers import pipeline
6
  from collections import Counter
7
 
8
  class TaskDashboardAI_Vietnamese:
9
  def __init__(self):
10
+ # Load Model ML (chỉ dùng khi cần thiết)
11
  try:
12
  self.classifier = pipeline(
13
  "zero-shot-classification",
 
15
  device=-1
16
  )
17
  self.use_ml = True
18
+ except:
 
19
  self.use_ml = False
20
 
21
  self.categories = [
22
  "Learning", "Practice", "Planning",
23
  "Organization", "Research", "Reflection"
24
  ]
25
+
26
+ # --- TỪ KHÓA ĐƯỢC PHÂN CẤP ĐỘ ƯU TIÊN ---
27
+ # Priority 1: Strong Signals (Gặp là chốt ngay)
28
+ # Priority 2: Common Actions (Cần kết hợp ngữ cảnh hoặc điểm số)
29
+ self.priority_keywords = {
30
  "Learning": {
31
+ "strong": ["tò mò", "hiểu ra", "nắm được", "biết thêm", "học được", "khám phá"],
32
+ "common": ["học", "xem video", "đọc sách", "tutorial", "lý thuyết"]
33
  },
34
  "Practice": {
35
+ "strong": ["code", "viết code", "debug", "fix bug", "thực hành", "làm bài tập", "nghịch code"],
36
+ "common": ["làm", "thử", "xây dựng", "implement", "chạy thử"]
37
  },
38
  "Planning": {
39
+ "strong": ["lên kế hoạch", "lập plan", "đặt mục tiêu", "roadmap", "chiến lược"],
40
+ "common": ["muốn", "sẽ", "dự định", "target", "mong muốn"]
41
  },
42
  "Organization": {
43
+ "strong": ["dọn dẹp", "sắp xếp folder", "tổ chức file", "setup máy", "cấu trúc lại"],
44
+ "common": ["lưu", "tạo folder", "quản lý", "gọn gàng"]
45
  },
46
  "Research": {
47
+ "strong": ["research", "khảo sát", "phân tích sâu", "so sánh giải pháp", "tìm hiểu kỹ"],
48
+ "common": ["tìm hiểu", "tìm kiếm", "đọc tài liệu", "search"]
49
  },
50
  "Reflection": {
51
+ "strong": ["nhận ra", "ý thức được", "reflect", "đánh giá bản thân", "journaling"],
52
+ "common": ["suy nghĩ", "thấy rằng", "cảm thấy", "viết nhật ký"]
53
  }
54
  }
55
 
56
  def clean_text(self, text):
57
+ return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip()
 
58
 
59
  def extract_tasks(self, text):
60
  lines = text.strip().split('\n')
 
66
  return tasks
67
 
68
  def classify_task(self, task):
69
+ """
70
+ Logic phân loại mới:
71
+ 1. Chuẩn hóa câu.
72
+ 2. Quét tìm 'Strong Keywords' trước. Nếu thấy -> Return ngay.
73
+ 3. Nếu không thấy Strong, quét 'Common Keywords' và tính điểm.
74
+ 4. Nếu điểm Common thấp hoặc mơ hồ -> Gọi Transformer.
75
+ """
76
  task_lower = task.lower()
 
77
 
78
+ # --- BƯỚC 1: QUÉT TỪ KHÓA MẠNH (STRONG KEYWORDS) ---
79
+ # Ưu tiên tuyệt đối. Nếu xuất hiện "tò mò" hay "debug", ta tin vào đó.
80
+ for category, keys in self.priority_keywords.items():
 
81
  for word in keys["strong"]:
82
  if word in task_lower:
83
+ return category
84
 
85
+ # --- BƯỚC 2: TÍNH ĐIỂM TỪ KHÓA THƯỜNG (COMMON KEYWORDS) ---
86
+ scores = {cat: 0 for cat in self.categories}
87
+ found_common = False
88
 
89
+ for category, keys in self.priority_keywords.items():
90
+ for word in keys["common"]:
91
+ if word in task_lower:
92
+ scores[category] += 1
93
+ found_common = True
94
 
95
+ # Nếu có điểm từ common keywords
96
+ if found_common:
97
+ max_score = max(scores.values())
98
+ # Nếu điểm cao nhất >= 2 (xuất hiện nhiều từ vựng cùng nhóm) -> Tin tưởng
99
+ if max_score >= 2:
100
+ return max(scores, key=scores.get)
101
+
102
+ # Nếu chỉ có 1 điểm (mơ hồ), ví dụ chỉ có từ "làm" hoặc "tìm hiểu"
103
+ # Ta sẽ kiểm tra xem có từ nào khác hỗ trợ không, nếu không thì chuyển sang ML
104
+ # Để tránh sai sót, ta cho qua bước ML để AI đoán ngữ cảnh
105
+
106
+ # --- BƯỚC 3: FALLBACK TO TRANSFORMER (AI) ---
107
  if self.use_ml:
108
  try:
109
  result = self.classifier(
110
  task,
111
  self.categories,
112
  multi_label=False,
113
+ hypothesis_template="Hoạt động này thuộc về mảng {}."
114
  )
115
+ # Chỉ lấy kết quả nếu độ tin cậy > 40%
116
+ if result['scores'][0] > 0.4:
117
  return result['labels'][0]
118
  except:
119
  pass
120
+
121
+ # --- BƯỚC 4: DEFAULT ---
122
+ # Nếu AI cũng không chắc, trả về category có điểm common cao nhất, hoặc 'Other'
123
+ if found_common:
124
+ return max(scores, key=scores.get)
125
+ return "Other"
126
 
127
  def create_donut_chart(self, cat_counts):
 
128
  if not cat_counts:
129
  fig = go.Figure()
130
+ fig.add_annotation(text="No data", showarrow=False)
131
  return fig
132
 
133
  labels = list(cat_counts.keys())
 
140
  hole=0.4,
141
  marker_colors=colors,
142
  textinfo='percent+label',
143
+ insidetextorientation='radial'
 
144
  )])
145
 
 
146
  fig.update_layout(
147
  title={
148
  'text': "📊 Daily Activity Distribution",
149
+ 'y': 0.95, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top'
 
 
 
150
  },
151
+ height=450,
152
  showlegend=True,
153
  legend=dict(
154
+ orientation="h",
155
+ yanchor="bottom",
156
+ y=-0.1,
157
+ xanchor="center",
158
+ x=0.5
159
  ),
160
+ margin=dict(t=60, b=60, l=20, r=20)
161
  )
162
  return fig
163
 
 
179
 
180
  chart = self.create_donut_chart(dict(cat_counter))
181
 
182
+ # HTML Output đẹp hơn
183
  summary_html = "<div style='font-family: sans-serif;'>"
184
+ summary_html += "<h3 style='border-bottom: 2px solid #eee; padding-bottom: 10px;'>📋 Detailed Classification</h3>"
185
  summary_html += "<ul style='list-style-type:none; padding:0;'>"
186
 
187
  color_map = {
 
192
  for task, cat in results:
193
  bg_color = color_map.get(cat, "#eeeeee")
194
  summary_html += f"""
195
+ <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);">
196
+ <span style="font-weight:bold; color:#555; font-size: 0.85em; text-transform:uppercase;">[{cat}]</span>
197
+ <span style="color:#333; margin-left: 8px;">{task}</span>
198
  </li>"""
199
  summary_html += "</ul>"
200
 
201
+ summary_html += "<h3 style='border-bottom: 2px solid #eee; padding-bottom: 10px; margin-top: 20px;'>📈 Summary</h3><ul>"
202
  total = sum(cat_counter.values())
203
  for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
204
  pct = (count / total) * 100
 
210
  # Initialize Agent
211
  ai_agent = TaskDashboardAI_Vietnamese()
212
 
 
213
  with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
214
  gr.Markdown("""
215
+ # 🇻🇳 Smart Task Dashboard
216
+ AI phân tích intent (ý định) dựa trên từ khóa ưu tiên và ngữ cảnh.
217
  """)
218
 
219
  with gr.Row():
220
  with gr.Column(scale=1):
221
  input_text = gr.Textbox(
222
+ label="📝 Nhập hoạt động hàng ngày",
223
+ 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...",
224
  lines=15
225
  )
226
+ btn = gr.Button("🚀 Phân tích", variant="primary", size="lg")
227
 
228
  gr.Examples(
229
  examples=[
230
+ """• tôi tò mò về cách hoạt động của neural network
231
+ • tôi nghịch code Python suốt buổi sáng
232
+ • tôi lên kế hoạch đi du lịch Đà Lạt
233
+ • tôi dọn dẹp lại đống file trên desktop
234
+ • tôi research về thị trường chứng khoán
235
+ • tôi nhận ra mình cần nghỉ ngơi nhiều hơn""",
 
 
 
236
  ],
237
  inputs=input_text
238
  )
239
 
240
  with gr.Column(scale=2):
241
+ chart_output = gr.Plot(label="📊 Biểu đồ phân bổ")
242
+ summary_output = gr.HTML(label="📋 Kết quả chi tiết")
243
 
244
  btn.click(
245
  fn=ai_agent.process,