AugustinHuang commited on
Commit
1fb7be3
·
verified ·
1 Parent(s): 784917b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -165
app.py CHANGED
@@ -8,208 +8,220 @@ from collections import Counter
8
 
9
  class TaskDashboardAI_Vietnamese:
10
  def __init__(self):
11
- # Model multilingual tốt hơn cho tiếng Việt
 
12
  try:
13
  self.classifier = pipeline(
14
  "zero-shot-classification",
15
- model="typeform/distilbert-base-multilingual-cased-mnli" # Support tiếng Việt tốt hơn
 
16
  )
17
  self.use_ml = True
18
- except:
 
19
  self.use_ml = False
20
 
21
- # Categories
22
  self.categories = [
23
  "Learning", "Practice", "Planning",
24
  "Organization", "Research", "Reflection"
25
  ]
26
 
27
- # Vietnamese keywords mapping (CHI TIẾT HƠN)
 
 
28
  self.keywords = {
29
- "Learning": [
30
- "học", "học được", "biết được", "video", "xem xong", "đọc",
31
- "tìm hiểu", "khám phá", "nghiên cứu", "course", "tutorial",
32
- "hiểu được", "nắm được", "learn", "study"
33
- ],
34
- "Practice": [
35
- "thực hành", "code", "viết code", "nghịch", "thử", "làm bài",
36
- "bài tập", "practice", "coding", "debug", "chạy thử",
37
- "implement", "xây dựng", "tạo ra", "nhớ"
38
- ],
39
- "Planning": [
40
- "dự định", "muốn", "sẽ", "dự kiến", "lên kế hoạch", "plan",
41
- "chiến lược", "mvp", "quick wins", "mục tiêu", "target",
42
- "roadmap", "lộ trình", "intend", "going to"
43
- ],
44
- "Organization": [
45
- "folder", "thư mục", "lưu trữ", "lưu", "tạo folder", "organize",
46
- "sắp xếp", "quản lý", "setup", "cấu trúc", "directory",
47
- "dọn dẹp", "organizing", "quyết định"
48
- ],
49
- "Research": [
50
- "tìm hiểu sâu", "research", "đọc tài liệu", "phân tích",
51
- "tìm kiếm thông tin", "survey", "investigate", "khảo sát",
52
- "đọc paper", "tìm data"
53
- ],
54
- "Reflection": [
55
- "ý thức được", "suy nghĩ", "reflect", "self-aware",
56
- "viết ra", "journal", "self-improvement",
57
- "đánh giá", "review bản thân"
58
- ]
59
  }
60
-
 
 
 
 
 
 
61
  def extract_tasks(self, text):
62
- """Tách text thành tasks - CẢI TIẾN"""
63
- # Remove empty lines và clean
64
  lines = text.strip().split('\n')
65
  tasks = []
66
-
67
  for line in lines:
68
- line = line.strip()
69
- # Remove bullet points và số
70
- line = re.sub(r'^[•\-\*\d\.\)]+\s*', '', line)
71
- if line and len(line) > 5: # Chỉ lấy dòng có ý nghĩa
72
- tasks.append(line)
73
-
74
  return tasks
75
-
76
- def classify_with_keywords(self, task):
77
- """Phân loại bằng keyword matching - CHI TIẾT HƠN"""
 
 
 
 
78
  task_lower = task.lower()
79
- scores = {}
80
-
81
- for category, keywords in self.keywords.items():
82
- match_count = 0
83
- for keyword in keywords:
84
- if keyword.lower() in task_lower:
85
- match_count += 1
86
- scores[category] = match_count
87
-
88
- # Tìm category có điểm cao nhất
89
- max_score = max(scores.values())
90
- if max_score == 0:
91
- return "Other" # Không match cái nào
92
-
93
- # Nếu có nhiều category cùng điểm, ưu tiên theo thứ tự
94
- top_categories = [cat for cat, score in scores.items() if score == max_score]
95
- return top_categories[0]
96
-
97
- def classify_with_ml(self, task):
98
- """Phân loại bằng ML model (backup)"""
99
- if not self.use_ml:
100
- return self.classify_with_keywords(task)
101
-
102
- try:
103
- result = self.classifier(
104
- task,
105
- self.categories,
106
- multi_label=False,
107
- hypothesis_template="This text is about {}."
108
- )
109
- # Chỉ tin tưởng nếu confidence > 0.3
110
- if result['scores'][0] > 0.4:
111
- return result['labels'][0]
112
- else:
113
- return self.classify_with_keywords(task) # Fallback to keywords
114
- except:
115
- return self.classify_with_keywords(task)
116
-
117
- def create_visualization(self, tasks_with_cats):
118
- """Tạo biểu đồ thông minh"""
119
- # Đếm category
120
- cat_counter = Counter([cat for _, cat in tasks_with_cats])
121
-
122
- if not cat_counter:
123
- # Default empty chart
124
  fig = go.Figure()
125
- fig.add_annotation(text="No tasks found!",
126
- xref="paper", yref="paper",
127
- x=0.5, y=0.5, showarrow=False)
128
- return fig, {}
129
-
130
- categories = list(cat_counter.keys())
131
- counts = list(cat_counter.values())
132
-
133
- # Chọn chart type dựa trên số category
134
- if len(categories) <= 5:
135
- # Pie/Donut chart
136
- fig = go.Figure(data=[go.Pie(
137
- labels=categories,
138
- values=counts,
139
- hole=0.3,
140
- marker_colors=px.colors.qualitative.Pastel,
141
- textinfo='percent+label',
142
- insidetextorientation='radial'
143
- )])
144
- fig.update_layout(
145
- title_text="📊 Task Distribution",
146
- height=500,
147
- showlegend=True
148
- )
149
-
150
- return fig, dict(cat_counter)
151
-
 
152
  def process(self, text):
153
- """Main processing function"""
 
 
 
154
  tasks = self.extract_tasks(text)
155
-
156
  if not tasks:
157
- return None, "❌ No valid tasks found. Please check your input format."
158
-
159
- # Classify từng task
160
  results = []
 
 
161
  for task in tasks:
162
- category = self.classify_with_keywords(task) # Ưu tiên keyword (ổn định hơn)
163
  results.append((task, category))
164
-
165
- # Tạo visualization
166
- fig, cat_counts = self.create_visualization(results)
167
-
168
- # Tạo summary
169
- summary = "📋 **Classification Details:**\n\n"
 
170
  for task, cat in results:
171
- summary += f"• **{cat}**: {task[:60]}...\n"
172
-
173
- summary += "\n📊 **Summary:**\n"
174
- for cat, count in sorted(cat_counts.items(), key=lambda x: x[1], reverse=True):
175
- percentage = (count / len(results)) * 100
176
- summary += f"• {cat}: {count} tasks ({percentage:.1f}%)\n"
177
-
178
- return fig, summary
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
- # Initialize
 
 
181
  ai_agent = TaskDashboardAI_Vietnamese()
182
 
183
- # Gradio UI
184
  with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
185
  gr.Markdown("""
186
- # 🇻 AI Task Dashboard for Vietnamese Text
187
- **Paste your daily tasks → Auto-classify → Beautiful Charts**
188
  """)
189
 
190
  with gr.Row():
191
  with gr.Column(scale=1):
192
  input_text = gr.Textbox(
193
- label="📝 Paste Vietnamese Tasks",
194
- placeholder="• tôi đã học Python\n• tôi đã thực hành web scraping\n• tôi muốn tạo dashboard...",
195
- lines=12
196
  )
197
- btn = gr.Button("🚀 Generate Dashboard", variant="primary", size="lg")
198
-
199
- with gr.Column(scale=2):
200
- chart_output = gr.Plot(label="📊 Dashboard")
201
- summary_output = gr.Textbox(label="📋 Results", lines=10)
202
-
203
- btn.click(
204
- fn=lambda text: ai_agent.process(text),
205
- inputs=input_text,
206
- outputs=[chart_output, summary_output]
207
- )
208
-
209
- # Example
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()
@@ -218,8 +230,23 @@ with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as
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
  demo.launch()
 
8
 
9
  class TaskDashboardAI_Vietnamese:
10
  def __init__(self):
11
+ # Khởi tạo Model ML (Zero-shot)
12
+ # Sử dụng model nhỏ nhẹ nhưng hỗ trợ đa ngôn ngữ tốt
13
  try:
14
  self.classifier = pipeline(
15
  "zero-shot-classification",
16
+ model="typeform/distilbert-base-multilingual-cased-mnli",
17
+ device=-1 # Chạy trên CPU, nếu có GPU thì đổi thành 0
18
  )
19
  self.use_ml = True
20
+ except Exception as e:
21
+ print(f"ML Model load failed: {e}")
22
  self.use_ml = False
23
 
24
+ # Categories chuẩn hóa
25
  self.categories = [
26
  "Learning", "Practice", "Planning",
27
  "Organization", "Research", "Reflection"
28
  ]
29
 
30
+ # --- CẢI TIẾN KEYWORDS ---
31
+ # Chia làm 2 loại: Common (chung chung) và Strong (đặc trưng mạnh)
32
+ # Strong keywords sẽ được tính điểm cao hơn để tăng accuracy
33
  self.keywords = {
34
+ "Learning": {
35
+ "common": ["học", "xem video", "đọc sách", "tutorial", "course", "khái niệm", "lý thuyết"],
36
+ "strong": ["hiểu ra", "nắm bắt", "biết thêm", "learned", "studied"]
37
+ },
38
+ "Practice": {
39
+ "common": ["làm bài tập", "thử", "nghịch", "code", "viết code", "implement", "xây dựng"],
40
+ "strong": ["debug", "fix bug", "chạy thử", "error", "sửa lỗi", "coding", "practice"]
41
+ },
42
+ "Planning": {
43
+ "common": ["muốn", "sẽ", "dự định", "lên kế hoạch", "target", "mục tiêu"],
44
+ "strong": ["roadmap", "MVP", "quick wins", "chiến lược", "deadline", "schedule"]
45
+ },
46
+ "Organization": {
47
+ "common": ["lưu", "tạo folder", "sắp xếp", "dọn dẹp", "quản lý file"],
48
+ "strong": ["directory", "structure", "organize", "setup environment", "config"]
49
+ },
50
+ "Research": {
51
+ "common": ["tìm hiểu", "tìm kiếm", "đọc tài liệu", "search google"],
52
+ "strong": ["research", "survey", "phân tích sâu", "so sánh", "investigate", "paper"]
53
+ },
54
+ "Reflection": {
55
+ "common": ["suy nghĩ", "nhận ra", "thấy rằng", "journal", "viết nhật ký"],
56
+ "strong": ["reflect", "ý thức", "đánh giá bản thân", "review", "self-aware", "cảm thấy"]
57
+ }
 
 
 
 
 
 
58
  }
59
+
60
+ def clean_text(self, text):
61
+ """Làm sạch văn bản đầu vào"""
62
+ # Xóa các ký tự đặc biệt đầu dòng, số thứ tự
63
+ text = re.sub(r'^[•\-\*\d\.\)]+\s*', '', text)
64
+ return text.strip()
65
+
66
  def extract_tasks(self, text):
67
+ """Tách text thành danh sách tasks"""
 
68
  lines = text.strip().split('\n')
69
  tasks = []
 
70
  for line in lines:
71
+ cleaned = self.clean_text(line)
72
+ if cleaned and len(cleaned) > 4: # Bỏ qua dòng quá ngắn
73
+ tasks.append(cleaned)
 
 
 
74
  return tasks
75
+
76
+ def classify_task(self, task):
77
+ """
78
+ Hybrid Classification:
79
+ 1. Tính điểm dựa trên Keyword (Weighted Score)
80
+ 2. Nếu điểm quá thấp hoặc nghi ngờ -> Dùng ML Model
81
+ """
82
  task_lower = task.lower()
83
+ scores = {cat: 0 for cat in self.categories}
84
+
85
+ # Bước 1: Keyword Matching với trọng số
86
+ for category, keys in self.keywords.items():
87
+ # Điểm cho từ common
88
+ for word in keys["common"]:
89
+ if word in task_lower:
90
+ scores[category] += 1
91
+ # Điểm cho từ strong (gấp đôi)
92
+ for word in keys["strong"]:
93
+ if word in task_lower:
94
+ scores[category] += 3
95
+
96
+ max_keyword_score = max(scores.values())
97
+
98
+ # Ngưỡng tin cậy của Keyword
99
+ # Nếu điểm cao nhất >= 2 (tức là có ít nhất 1 strong word hoặc 2 common words)
100
+ if max_keyword_score >= 2:
101
+ # Trả về category có điểm cao nhất
102
+ best_cat = max(scores, key=scores.get)
103
+ return best_cat
104
+
105
+ # Bước 2: Fallback to ML nếu keyword không rõ ràng
106
+ if self.use_ml:
107
+ try:
108
+ result = self.classifier(
109
+ task,
110
+ self.categories,
111
+ multi_label=False,
112
+ hypothesis_template="This daily activity is related to {}."
113
+ )
114
+ # Chỉ lấy kết quả nếu confidence > 0.35
115
+ if result['scores'][0] > 0.35:
116
+ return result['labels'][0]
117
+ except:
118
+ pass
119
+
120
+ # Bước 3: Nếu cả 2 đều fail, trả về category có điểm keyword cao nhất (dù thấp)
121
+ # Hoặc trả về 'Other' nếu muốn strict
122
+ best_cat = max(scores, key=scores.get)
123
+ return best_cat if max_keyword_score > 0 else "Other"
124
+
125
+ def create_donut_chart(self, cat_counts):
126
+ """Tạo biểu đồ tròn Donut Chart duy nhất"""
127
+ if not cat_counts:
128
  fig = go.Figure()
129
+ fig.add_annotation(text="No data to display", showarrow=False, font_size=20)
130
+ return fig
131
+
132
+ labels = list(cat_counts.keys())
133
+ values = list(cat_counts.values())
134
+
135
+ # Màu sắc pastel dễ nhìn
136
+ colors = px.colors.qualitative.Pastel
137
+
138
+ fig = go.Figure(data=[go.Pie(
139
+ labels=labels,
140
+ values=values,
141
+ hole=0.4, # Tạo lỗ tròn ở giữa (Donut)
142
+ marker_colors=colors,
143
+ textinfo='percent+label',
144
+ insidetextorientation='radial',
145
+ hovertemplate="<b>%{label}</b><br>Tasks: %{value}<extra></extra>"
146
+ )])
147
+
148
+ fig.update_layout(
149
+ title_text="📊 Daily Activity Distribution",
150
+ title_x=0.5,
151
+ height=400,
152
+ showlegend=True,
153
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
154
+ )
155
+ return fig
156
+
157
  def process(self, text):
158
+ """Hàm xử lý chính"""
159
+ if not text or not text.strip():
160
+ return None, "⚠️ Please enter some text first."
161
+
162
  tasks = self.extract_tasks(text)
 
163
  if not tasks:
164
+ return None, "❌ No valid tasks found. Try using bullet points (•) or new lines."
165
+
 
166
  results = []
167
+ cat_counter = Counter()
168
+
169
  for task in tasks:
170
+ category = self.classify_task(task)
171
  results.append((task, category))
172
+ cat_counter[category] += 1
173
+
174
+ # Tạo biểu đồ
175
+ chart = self.create_donut_chart(dict(cat_counter))
176
+
177
+ # Tạo báo cáo chi tiết
178
+ summary_html = "<h3>📋 Detailed Classification</h3><ul style='list-style-type:none; padding:0;'>"
179
  for task, cat in results:
180
+ # Map màu cho badge
181
+ color_map = {
182
+ "Learning": "#a6cee3", "Practice": "#fb9a99", "Planning": "#b2df8a",
183
+ "Organization": "#fdbf6f", "Research": "#cab2d6", "Reflection": "#ffff99", "Other": "#cccccc"
184
+ }
185
+ bg_color = color_map.get(cat, "#eeeeee")
186
+
187
+ summary_html += f"""
188
+ <li style="margin-bottom: 8px; padding: 8px; background-color: #f9f9f9; border-left: 4px solid {bg_color};">
189
+ <span style="font-weight:bold; color:#333;">[{cat}]</span> {task}
190
+ </li>"""
191
+ summary_html += "</ul>"
192
+
193
+ # Thống kê tổng quan
194
+ summary_html += "<hr><h3>📈 Summary Statistics</h3><ul>"
195
+ total = sum(cat_counter.values())
196
+ for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
197
+ pct = (count / total) * 100
198
+ summary_html += f"<li><b>{cat}</b>: {count} tasks ({pct:.1f}%)</li>"
199
+ summary_html += "</ul>"
200
 
201
+ return chart, summary_html
202
+
203
+ # Initialize Agent
204
  ai_agent = TaskDashboardAI_Vietnamese()
205
 
206
+ # Gradio UI Setup
207
  with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
208
  gr.Markdown("""
209
+ # 🇻🇳 AI Task Dashboard for Vietnamese
210
+ Paste your daily log, and let AI categorize your activities into Learning, Practice, Planning, etc.
211
  """)
212
 
213
  with gr.Row():
214
  with gr.Column(scale=1):
215
  input_text = gr.Textbox(
216
+ label="📝 Paste your daily notes here",
217
+ placeholder="Example:\n• tôi đã học Python\n• fix bug login page\n• lên kế hoạch cho tuần sau...",
218
+ lines=15
219
  )
220
+ btn = gr.Button("🚀 Analyze & Visualize", variant="primary", size="lg")
221
+
222
+ gr.Examples(
223
+ examples=[
224
+ """• tôi đã nhớ được 1 dạng pattern phần giải thích
 
 
 
 
 
 
 
 
 
 
 
225
  • tôi đã ý thức được tầm quan trọng của quick wins
226
  • tôi đã quyết định viết những dòng này
227
  • tôi đã nghịch Python dù chưa biết def()
 
230
  • tôi đã tìm hiểu về tập đoàn nhà nước
231
  • tôi đã lập ra 2 folders
232
  • tôi đã sửa 1 số bài toán làm sai""",
233
+ """• Research về ReactJS hooks
234
+ • Lên plan cho dự án cá nhân
235
+ • Dọn dẹp folder Downloads
236
+ • Viết journal buổi tối
237
+ • Thực hành code LeetCode"""
238
+ ],
239
+ inputs=input_text
240
+ )
241
+
242
+ with gr.Column(scale=2):
243
+ chart_output = gr.Plot(label="📊 Activity Distribution")
244
+ summary_output = gr.HTML(label="📋 Analysis Results") # Đổi sang HTML để đẹp hơn
245
+
246
+ btn.click(
247
+ fn=ai_agent.process,
248
+ inputs=input_text,
249
+ outputs=[chart_output, summary_output]
250
  )
251
 
252
  demo.launch()