AugustinHuang commited on
Commit
75afca8
·
verified ·
1 Parent(s): 74b9bb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -139
app.py CHANGED
@@ -1,208 +1,238 @@
1
- # app.py - Gradio App cho Hugging Face Spaces
2
  import gradio as gr
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
- from plotly.subplots import make_subplots
6
  import pandas as pd
7
  import re
8
  from transformers import pipeline
9
- import io
10
- import base64
11
 
12
- class TaskDashboardAI:
13
  def __init__(self):
14
- # Load AI models
15
- self.classifier = pipeline(
16
- "zero-shot-classification",
17
- model="facebook/bart-large-mnli"
18
- )
19
-
20
- # Categories mặc định
21
- self.default_categories = [
22
- "Learning", "Practice", "Planning/Ideas",
23
- "Research", "Organization"
 
 
 
 
24
  ]
25
 
26
- # Keywords mapping
27
- self.category_keywords = {
28
- "Learning": ["học", "video", "xem", "tìm hiểu", "khám phá", "study", "learn"],
29
- "Practice": ["thực hành", "practice", "code", "nghịch", "thử", "làm"],
30
- "Planning/Ideas": ["dự định", "muốn", "sẽ", "plan", "chiến lược", "mvp", "tò mò"],
31
- "Organization": ["folder", "lưu trữ", "tạo", "setup", "organize", "quản lý"],
32
- "Research": ["nghiên cứu", "tìm hiểu", "research", "đọc", "phân tích"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  }
34
 
35
- def extract_tasks_from_text(self, text):
36
- """Tách text thành từng task"""
37
- # Pattern: tìm các dòng bắt đầu bằng "•" hoặc số
38
- tasks = re.split(r'[•\-\*]|\n\d+\.', text)
39
- tasks = [t.strip() for t in tasks if t.strip() and len(t.strip()) > 10]
 
 
 
 
 
 
 
 
40
  return tasks
41
 
42
- def classify_task(self, task):
43
- """Dùng AI để phân loại task"""
44
- # Cách 1: Zero-shot classification
45
- result = self.classifier(
46
- task,
47
- self.default_categories,
48
- multi_label=False
49
- )
50
- return result['labels'][0]
51
-
52
- def classify_task_keywords(self, task):
53
- """Phân loại bằng keywords (backup)"""
54
  task_lower = task.lower()
55
  scores = {}
56
 
57
- for category, keywords in self.category_keywords.items():
58
- score = sum(1 for kw in keywords if kw in task_lower)
59
- scores[category] = score
60
-
61
- return max(scores, key=scores.get) if max(scores.values()) > 0 else "Other"
 
 
 
 
 
 
 
 
 
 
62
 
63
- def determine_chart_type(self, data_dict):
64
- """AI quyết định loại biểu đồ phù hợp"""
65
- n_categories = len(data_dict)
66
- total_items = sum(data_dict.values())
67
-
68
- if n_categories <= 3:
69
- return "pie"
70
- elif n_categories <= 6:
71
- return "donut"
72
- elif n_categories <= 10:
73
- return "bar"
74
- else:
75
- return "horizontal_bar"
 
 
 
 
 
 
76
 
77
- def create_dashboard(self, tasks_with_categories):
78
- """Tạo dashboard thông minh"""
79
- # Đếm tasks theo category
80
- category_counts = {}
81
- for task, category in tasks_with_categories:
82
- category_counts[category] = category_counts.get(category, 0) + 1
83
-
84
- # Chọn chart type
85
- chart_type = self.determine_chart_type(category_counts)
86
-
87
- # Tạo figure
88
- categories = list(category_counts.keys())
89
- counts = list(category_counts.values())
90
- colors = px.colors.qualitative.Pastel
91
-
92
- if chart_type in ["pie", "donut"]:
 
 
 
93
  fig = go.Figure(data=[go.Pie(
94
  labels=categories,
95
  values=counts,
96
- hole=0.4 if chart_type == "donut" else 0,
97
- marker_colors=colors,
98
  textinfo='percent+label',
99
  insidetextorientation='radial'
100
  )])
101
  fig.update_layout(
102
- title_text="📊 Task Distribution by Category",
103
- height=600,
104
  showlegend=True
105
  )
106
-
107
- elif chart_type == "bar":
108
  fig = px.bar(
109
  x=categories,
110
  y=counts,
111
  color=categories,
112
- color_discrete_sequence=colors,
113
- title="📊 Task Distribution by Category"
114
  )
115
  fig.update_layout(
116
- height=600,
117
  showlegend=False,
118
  xaxis_title="Category",
119
- yaxis_title="Number of Tasks"
120
  )
121
 
122
- else: # horizontal_bar
123
- fig = px.bar(
124
- y=categories,
125
- x=counts,
126
- orientation='h',
127
- color=categories,
128
- color_discrete_sequence=colors,
129
- title="📊 Task Distribution by Category"
130
- )
131
- fig.update_layout(
132
- height=600,
133
- showlegend=False
134
- )
135
-
136
- return fig, category_counts
137
 
138
- def process_text(self, text):
139
- """Xử lý text input và tạo dashboard"""
140
- # Extract tasks
141
- tasks = self.extract_tasks_from_text(text)
 
 
142
 
143
  # Classify từng task
144
- tasks_with_categories = []
145
  for task in tasks:
146
- # Dùng AI classification
147
- category = self.classify_task(task)
148
- tasks_with_categories.append((task, category))
149
 
150
- # Tạo dashboard
151
- fig, category_counts = self.create_dashboard(tasks_with_categories)
152
 
153
- # Tạo summary text
154
- summary = "📋 **Classification Results:**\n\n"
155
- for task, category in tasks_with_categories:
156
- summary += f"✓ **{category}**: {task[:50]}...\n"
157
 
158
- summary += f"\n📊 **Summary:**\n"
159
- for cat, count in category_counts.items():
160
- summary += f"• {cat}: {count} tasks\n"
 
161
 
162
- return fig, summary, tasks_with_categories
163
-
164
- # Gradio Interface
165
- dashboard_ai = TaskDashboardAI()
166
 
167
- def create_dashboard_from_text(text):
168
- fig, summary, tasks = dashboard_ai.process_text(text)
169
- return fig, summary
170
 
171
- # Tạo Gradio UI
172
- with gr.Blocks(title="AI Task Dashboard Generator", theme=gr.themes.Soft()) as demo:
173
  gr.Markdown("""
174
- # 🤖 AI Task Dashboard Generator
175
- **Paste your daily tasks → AI classifies → Auto creates beautiful charts**
176
  """)
177
 
178
  with gr.Row():
179
  with gr.Column(scale=1):
180
  input_text = gr.Textbox(
181
- label="📝 Paste Your Tasks Here",
182
- placeholder="• tôi đã học Python\n• tôi đã thực hành web scraping\n...",
183
- lines=15
184
  )
185
- btn = gr.Button("🚀 Generate Dashboard", variant="primary")
186
 
187
  with gr.Column(scale=2):
188
  chart_output = gr.Plot(label="📊 Dashboard")
189
- summary_output = gr.Textbox(label="📋 Classification Summary", lines=10)
190
 
191
  btn.click(
192
- fn=create_dashboard_from_text,
193
  inputs=input_text,
194
  outputs=[chart_output, summary_output]
195
  )
196
 
197
- # Examples
198
  gr.Examples(
199
  examples=[
200
- """• tôi đã học Python cơ bản
201
- • tôi đã xem video về machine learning
202
- • tôi muốn tạo dashboard tự động
203
- • tôi đã thực hành web scraping
204
- • tôi cần organize folders
205
- • tôi sẽ nghiên cứu về AI agents""",
 
 
 
206
  ],
207
  inputs=input_text
208
  )
 
 
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
+ # 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"
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"
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
+ "nhớ được", "ý thức được", "suy nghĩ", "reflect", "self-aware",
56
+ "quyết định", "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.3:
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
+ else:
150
+ # Bar chart
151
  fig = px.bar(
152
  x=categories,
153
  y=counts,
154
  color=categories,
155
+ color_discrete_sequence=px.colors.qualitative.Pastel,
156
+ title="📊 Task Distribution"
157
  )
158
  fig.update_layout(
159
+ height=500,
160
  showlegend=False,
161
  xaxis_title="Category",
162
+ yaxis_title="Count"
163
  )
164
 
165
+ return fig, dict(cat_counter)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
+ def process(self, text):
168
+ """Main processing function"""
169
+ tasks = self.extract_tasks(text)
170
+
171
+ if not tasks:
172
+ return None, "❌ No valid tasks found. Please check your input format."
173
 
174
  # Classify từng task
175
+ results = []
176
  for task in tasks:
177
+ category = self.classify_with_keywords(task) # Ưu tiên keyword (ổn định hơn)
178
+ results.append((task, category))
 
179
 
180
+ # Tạo visualization
181
+ fig, cat_counts = self.create_visualization(results)
182
 
183
+ # Tạo summary
184
+ summary = "📋 **Classification Details:**\n\n"
185
+ for task, cat in results:
186
+ summary += f"• **{cat}**: {task[:60]}...\n"
187
 
188
+ summary += "\n📊 **Summary:**\n"
189
+ for cat, count in sorted(cat_counts.items(), key=lambda x: x[1], reverse=True):
190
+ percentage = (count / len(results)) * 100
191
+ summary += f"• {cat}: {count} tasks ({percentage:.1f}%)\n"
192
 
193
+ return fig, summary
 
 
 
194
 
195
+ # Initialize
196
+ ai_agent = TaskDashboardAI_Vietnamese()
 
197
 
198
+ # Gradio UI
199
+ with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
200
  gr.Markdown("""
201
+ # 🇻 AI Task Dashboard for Vietnamese Text
202
+ **Paste your daily tasks → Auto-classify → Beautiful Charts**
203
  """)
204
 
205
  with gr.Row():
206
  with gr.Column(scale=1):
207
  input_text = gr.Textbox(
208
+ label="📝 Paste Vietnamese Tasks",
209
+ placeholder="• tôi đã học Python\n• tôi đã thực hành web scraping\n• tôi muốn tạo dashboard...",
210
+ lines=12
211
  )
212
+ btn = gr.Button("🚀 Generate Dashboard", variant="primary", size="lg")
213
 
214
  with gr.Column(scale=2):
215
  chart_output = gr.Plot(label="📊 Dashboard")
216
+ summary_output = gr.Textbox(label="📋 Results", lines=10)
217
 
218
  btn.click(
219
+ fn=lambda text: ai_agent.process(text),
220
  inputs=input_text,
221
  outputs=[chart_output, summary_output]
222
  )
223
 
224
+ # Example
225
  gr.Examples(
226
  examples=[
227
+ """• tôi đã nhớ được 1 dạng pattern phần giải thích
228
+ • tôi đã ý thức được tầm quan trọng của quick wins
229
+ • tôi đã quyết định viết những dòng này
230
+ • tôi đã nghịch Python dù chưa biết def()
231
+ • tôi đã xem xong 1 video về hàm def()
232
+ • tôi đã thực hành web scraping
233
+ • tôi đã tìm hiểu về tập đoàn nhà nước
234
+ • tôi đã lập ra 2 folders
235
+ • tôi đã sửa 1 số bài toán làm sai""",
236
  ],
237
  inputs=input_text
238
  )