Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,28 +8,24 @@ from collections import Counter
|
|
| 8 |
|
| 9 |
class TaskDashboardAI_Vietnamese:
|
| 10 |
def __init__(self):
|
| 11 |
-
# Khởi tạo Model ML
|
| 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
|
| 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 |
-
#
|
| 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"],
|
|
@@ -58,51 +54,35 @@ class TaskDashboardAI_Vietnamese:
|
|
| 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:
|
| 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 |
-
|
| 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(
|
|
@@ -111,19 +91,16 @@ class TaskDashboardAI_Vietnamese:
|
|
| 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 |
-
"""
|
| 127 |
if not cat_counts:
|
| 128 |
fig = go.Figure()
|
| 129 |
fig.add_annotation(text="No data to display", showarrow=False, font_size=20)
|
|
@@ -131,37 +108,47 @@ class TaskDashboardAI_Vietnamese:
|
|
| 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,
|
| 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 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
showlegend=True,
|
| 153 |
-
legend=dict(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 165 |
|
| 166 |
results = []
|
| 167 |
cat_counter = Counter()
|
|
@@ -171,50 +158,51 @@ class TaskDashboardAI_Vietnamese:
|
|
| 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
|
| 178 |
-
summary_html = "<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
| 189 |
-
<span style="font-weight:bold; color:#
|
|
|
|
| 190 |
</li>"""
|
| 191 |
summary_html += "</ul>"
|
| 192 |
|
| 193 |
-
#
|
| 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
|
| 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 |
-
|
| 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
|
| 218 |
lines=15
|
| 219 |
)
|
| 220 |
btn = gr.Button("🚀 Analyze & Visualize", variant="primary", size="lg")
|
|
@@ -230,22 +218,18 @@ with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as
|
|
| 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 |
-
|
|
|
|
| 244 |
|
| 245 |
btn.click(
|
| 246 |
fn=ai_agent.process,
|
| 247 |
inputs=input_text,
|
| 248 |
-
outputs=[summary_output]
|
| 249 |
)
|
| 250 |
|
| 251 |
demo.launch()
|
|
|
|
| 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",
|
| 15 |
model="typeform/distilbert-base-multilingual-cased-mnli",
|
| 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"],
|
|
|
|
| 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')
|
| 62 |
tasks = []
|
| 63 |
for line in lines:
|
| 64 |
cleaned = self.clean_text(line)
|
| 65 |
+
if cleaned and len(cleaned) > 4:
|
| 66 |
tasks.append(cleaned)
|
| 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(
|
|
|
|
| 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)
|
|
|
|
| 108 |
|
| 109 |
labels = list(cat_counts.keys())
|
| 110 |
values = list(cat_counts.values())
|
|
|
|
|
|
|
| 111 |
colors = px.colors.qualitative.Pastel
|
| 112 |
|
| 113 |
fig = go.Figure(data=[go.Pie(
|
| 114 |
labels=labels,
|
| 115 |
values=values,
|
| 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 |
|
| 145 |
def process(self, text):
|
|
|
|
| 146 |
if not text or not text.strip():
|
| 147 |
return None, "⚠️ Please enter some text first."
|
| 148 |
|
| 149 |
tasks = self.extract_tasks(text)
|
| 150 |
if not tasks:
|
| 151 |
+
return None, "❌ No valid tasks found."
|
| 152 |
|
| 153 |
results = []
|
| 154 |
cat_counter = Counter()
|
|
|
|
| 158 |
results.append((task, category))
|
| 159 |
cat_counter[category] += 1
|
| 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 = {
|
| 169 |
+
"Learning": "#a6cee3", "Practice": "#fb9a99", "Planning": "#b2df8a",
|
| 170 |
+
"Organization": "#fdbf6f", "Research": "#cab2d6", "Reflection": "#ffff99", "Other": "#cccccc"
|
| 171 |
+
}
|
| 172 |
+
|
| 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
|
| 186 |
+
summary_html += f"<li style='padding: 5px 0;'><b>{cat}</b>: {count} tasks ({pct:.1f}%)</li>"
|
| 187 |
+
summary_html += "</ul></div>"
|
| 188 |
|
| 189 |
return chart, summary_html
|
| 190 |
|
| 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")
|
|
|
|
| 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,
|
| 231 |
inputs=input_text,
|
| 232 |
+
outputs=[chart_output, summary_output]
|
| 233 |
)
|
| 234 |
|
| 235 |
demo.launch()
|