Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,227 +1,180 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import plotly.express as px
|
| 3 |
import plotly.graph_objects as go
|
|
|
|
| 4 |
import re
|
| 5 |
import json
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
class TaskDashboardAI_Vietnamese:
|
| 9 |
-
def __init__(self
|
| 10 |
-
self.
|
| 11 |
-
self.
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
"
|
| 15 |
-
"Organization", "
|
| 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()
|
| 55 |
|
| 56 |
def extract_tasks(self, text):
|
| 57 |
lines = text.strip().split('\n')
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 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 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 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
|
| 80 |
except Exception as e:
|
| 81 |
-
|
| 82 |
-
return None
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
return
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
colors = px.colors.qualitative.Pastel
|
| 93 |
-
|
| 94 |
-
fig
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 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
|
| 110 |
-
|
| 111 |
-
if not
|
| 112 |
-
return None, "⚠️ Vui lòng nhập hoạt động.", ""
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
#
|
| 122 |
-
|
| 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 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
<
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 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 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
)
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 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 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import plotly.graph_objects as go
|
| 3 |
+
import plotly.express as px
|
| 4 |
import re
|
| 5 |
import json
|
| 6 |
+
from collections import Counter
|
| 7 |
+
|
| 8 |
+
# Kiểm tra thư viện Groq
|
| 9 |
+
try:
|
| 10 |
+
from groq import Groq
|
| 11 |
+
GROQ_AVAILABLE = True
|
| 12 |
+
except ImportError:
|
| 13 |
+
GROQ_AVAILABLE = False
|
| 14 |
|
| 15 |
class TaskDashboardAI_Vietnamese:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
self.categories = ["Learning", "Practice", "Planning", "Organization", "Research", "Reflection"]
|
| 18 |
+
self.priority_keywords = {
|
| 19 |
+
"Learning": {"strong": ["tò mò", "hiểu ra", "nắm được", "biết thêm", "học được", "khám phá"], "common": ["học", "xem video", "đọc sách", "tutorial", "lý thuyết"]},
|
| 20 |
+
"Practice": {"strong": ["code", "viết code", "debug", "fix bug", "thực hành", "làm bài tập", "nghịch code"], "common": ["làm", "thử", "xây dựng", "implement", "chạy thử"]},
|
| 21 |
+
"Planning": {"strong": ["lên kế hoạch", "lập plan", "đặt mục tiêu", "roadmap", "chiến lược"], "common": ["muốn", "sẽ", "dự định", "target", "mong muốn"]},
|
| 22 |
+
"Organization": {"strong": ["dọn dẹp", "sắp xếp folder", "tổ chức file", "setup máy", "cấu trúc lại"], "common": ["lưu", "tạo folder", "quản lý", "gọn gàng"]},
|
| 23 |
+
"Research": {"strong": ["research", "khảo sát", "phân tích sâu", "so sánh giải pháp", "tìm hiểu kỹ"], "common": ["tìm hiểu", "tìm kiếm", "đọc tài liệu", "search"]},
|
| 24 |
+
"Reflection": {"strong": ["nhận ra", "ý thức được", "reflect", "đánh giá bản thân", "journaling"], "common": ["suy nghĩ", "thấy rằng", "cảm thấy", "viết nhật ký"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
+
self.sentiment_labels = ["Quyết tâm", "Bối rối", "Buồn", "Sợ hãi", "Chiêm nghiệm", "Tự ti", "Khác"]
|
| 27 |
|
| 28 |
def clean_text(self, text):
|
| 29 |
return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip()
|
| 30 |
|
| 31 |
def extract_tasks(self, text):
|
| 32 |
lines = text.strip().split('\n')
|
| 33 |
+
return [self.clean_text(line) for line in lines if self.clean_text(line) and len(self.clean_text(line)) > 4]
|
| 34 |
+
|
| 35 |
+
def _call_groq_llm(self, prompt, api_key):
|
| 36 |
+
if not GROQ_AVAILABLE or not api_key: return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
+
client = Groq(api_key=api_key)
|
| 39 |
+
response = client.chat.completions.create(
|
| 40 |
+
model="llama-3.1-8b-instant", # Có thể đổi thành llama-3.3-70b-versatile nếu cần độ chính xác cao hơn
|
| 41 |
+
messages=[{"role": "user", "content": prompt}],
|
| 42 |
+
temperature=0.2, max_tokens=400
|
|
|
|
|
|
|
|
|
|
| 43 |
)
|
| 44 |
+
return response.choices[0].message.content
|
| 45 |
except Exception as e:
|
| 46 |
+
return f"⚠️ Lỗi Groq: {str(e)}"
|
|
|
|
| 47 |
|
| 48 |
+
def classify_task(self, task, api_key):
|
| 49 |
+
task_lower = task.lower()
|
| 50 |
+
# 1. Quét Strong Keywords
|
| 51 |
+
for cat, keys in self.priority_keywords.items():
|
| 52 |
+
if any(word in task_lower for word in keys["strong"]): return cat
|
| 53 |
+
|
| 54 |
+
# 2. Tính điểm Common Keywords
|
| 55 |
+
scores = {cat: 0 for cat in self.categories}
|
| 56 |
+
found_common = False
|
| 57 |
+
for cat, keys in self.priority_keywords.items():
|
| 58 |
+
for word in keys["common"]:
|
| 59 |
+
if word in task_lower:
|
| 60 |
+
scores[cat] += 1; found_common = True
|
| 61 |
+
|
| 62 |
+
if found_common and max(scores.values()) >= 2:
|
| 63 |
+
return max(scores, key=scores.get)
|
| 64 |
+
|
| 65 |
+
# 3. Fallback Llama 3 (Chỉ gọi khi Python chưa rõ)
|
| 66 |
+
if api_key and GROQ_AVAILABLE:
|
| 67 |
+
prompt = f"Phân loại hoạt động sau vào đúng 1 nhóm: {self.categories}. Chỉ trả về tên nhóm. Hoạt động: '{task}'"
|
| 68 |
+
res = self._call_groq_llm(prompt, api_key)
|
| 69 |
+
if res:
|
| 70 |
+
clean_res = res.replace("```json", "").replace("```", "").strip()
|
| 71 |
+
for cat in self.categories:
|
| 72 |
+
if cat.lower() in clean_res.lower(): return cat
|
| 73 |
+
return max(scores, key=scores.get) if found_common else "Other"
|
| 74 |
+
|
| 75 |
+
def analyze_sentiment(self, text, api_key):
|
| 76 |
+
if not api_key or not GROQ_AVAILABLE: return {k: 0 for k in self.sentiment_labels}
|
| 77 |
+
prompt = f"""Phân tích cảm xúc ngầm ẩn trong đoạn văn bản tiếng Việt sau. Trả về JSON DUY NHẤT theo đúng format:
|
| 78 |
+
{{
|
| 79 |
+
"Quyết tâm": %, "Bối rối": %, "Buồn": %, "Sợ hãi": %, "Chiêm nghiệm": %, "Tự ti": %, "Khác": %
|
| 80 |
+
}}
|
| 81 |
+
Tổng phải bằng 100. KHÔNG thêm bất kỳ text nào ngoài JSON.
|
| 82 |
+
Văn bản: {text}"""
|
| 83 |
+
res = self._call_groq_llm(prompt, api_key)
|
| 84 |
+
if not res or res.startswith("⚠️"): return {k: 0 for k in self.sentiment_labels}
|
| 85 |
+
try:
|
| 86 |
+
# Trích xuất JSON an toàn
|
| 87 |
+
match = re.search(r'\{.*\}', res, re.DOTALL)
|
| 88 |
+
data = json.loads(match.group(0))
|
| 89 |
+
return {k: data.get(k, 0) for k in self.sentiment_labels}
|
| 90 |
+
except: return {k: 0 for k in self.sentiment_labels}
|
| 91 |
+
|
| 92 |
+
def create_donut_chart(self, cat_counts):
|
| 93 |
+
if not cat_counts: return go.Figure().add_annotation(text="Chưa có dữ liệu", showarrow=False)
|
| 94 |
+
labels, values = list(cat_counts.keys()), list(cat_counts.values())
|
| 95 |
colors = px.colors.qualitative.Pastel
|
| 96 |
+
fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=0.4, marker_colors=colors, textinfo='percent+label', insidetextorientation='radial')])
|
| 97 |
+
fig.update_layout(title={'text': "📊 Daily Activity Distribution", 'y':0.95, 'x':0.5, 'xanchor':'center', 'yanchor':'top'}, height=420, margin=dict(t=60, b=40, l=20, r=20), showlegend=True, legend=dict(orientation="h", yanchor="bottom", y=-0.1, xanchor="center", x=0.5))
|
| 98 |
+
return fig
|
| 99 |
+
|
| 100 |
+
def create_sentiment_chart(self, sentiment_data):
|
| 101 |
+
fig = go.Figure()
|
| 102 |
+
fig.add_trace(go.Bar(x=list(sentiment_data.values()), y=list(sentiment_data.keys()), orientation='h', marker_color=["#a6cee3","#fb9a99","#b2df8a","#fdbf6f","#cab2d6","#ffff99","#cccccc"], text=[f"{v}%" for v in sentiment_data.values()], textposition='outside'))
|
| 103 |
+
fig.update_layout(title="🧠 Phân Tích Cảm Xúc (%)", xaxis=dict(range=[0, 105], title="Phần trăm"), yaxis=dict(title="Cảm xúc", autorange="reversed"), margin=dict(l=110, r=30, t=50, b=50), height=380, bargap=0.3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
return fig
|
| 105 |
|
| 106 |
def process(self, text, api_key):
|
| 107 |
+
if not text or not text.strip(): return None, None, "⚠️ Vui lòng nhập hoạt động trước."
|
| 108 |
+
tasks = self.extract_tasks(text)
|
| 109 |
+
if not tasks: return None, None, "❌ Không tìm thấy task hợp lệ (cần >4 ký tự)."
|
|
|
|
| 110 |
|
| 111 |
+
results, cat_counter = [], Counter()
|
| 112 |
+
for t in tasks:
|
| 113 |
+
cat = self.classify_task(t, api_key)
|
| 114 |
+
results.append((t, cat)); cat_counter[cat] += 1
|
| 115 |
|
| 116 |
+
chart = self.create_donut_chart(dict(cat_counter))
|
| 117 |
+
sentiment = self.analyze_sentiment(text, api_key)
|
| 118 |
+
sentiment_chart = self.create_sentiment_chart(sentiment)
|
| 119 |
+
|
| 120 |
+
# HTML Detailed Classification
|
| 121 |
+
color_map = {"Learning":"#a6cee3","Practice":"#fb9a99","Planning":"#b2df8a","Organization":"#fdbf6f","Research":"#cab2d6","Reflection":"#ffff99","Other":"#cccccc"}
|
| 122 |
+
html = "<div style='font-family:sans-serif;'><h3 style='border-bottom:2px solid #eee;padding-bottom:10px;'>📋 Detailed Classification</h3><ul style='list-style:none;padding:0;'>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
for task, cat in results:
|
| 124 |
+
bg = color_map.get(cat, "#eee")
|
| 125 |
+
html += f'<li style="margin-bottom:8px;padding:10px;background:#fff;border-left:5px solid {bg};box-shadow:0 1px 3px rgba(0,0,0,0.05);"><span style="font-weight:bold;color:#555;font-size:0.85em;text-transform:uppercase;">[{cat}]</span> <span style="color:#333;margin-left:8px;">{task}</span></li>'
|
| 126 |
+
html += "</ul><h3 style='border-bottom:2px solid #eee;padding-bottom:10px;margin-top:20px;'>📈 Summary</h3><ul>"
|
| 127 |
+
total = sum(cat_counter.values())
|
| 128 |
+
for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
|
| 129 |
+
html += f'<li style="padding:5px 0;"><b>{cat}</b>: {count} tasks ({(count/total)*100:.1f}%)</li>'
|
| 130 |
+
html += "</ul></div>"
|
| 131 |
+
return chart, sentiment_chart, html
|
| 132 |
+
|
| 133 |
+
ai_agent = TaskDashboardAI_Vietnamese()
|
| 134 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
|
| 136 |
+
gr.Markdown("# 🇻🇳 Smart Task Dashboard AI\n`AI phân tích Intent & Cảm xúc hàng ngày, hỗ trợ Llama 3 (Groq) cho các trường hợp phức tạp.`")
|
|
|
|
|
|
|
|
|
|
| 137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
with gr.Row():
|
| 139 |
+
# CỘT TRÁI: Nhập liệu + Gợi ý
|
| 140 |
with gr.Column(scale=1):
|
| 141 |
+
input_text = gr.Textbox(label="📝 Nhập hoạt động hàng ngày", lines=10, placeholder="• 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...", elem_id="input_box")
|
| 142 |
+
btn = gr.Button("🚀 Phân tích & Cảm xúc", variant="primary", size="lg")
|
| 143 |
+
gr.Examples(examples=[
|
| 144 |
+
"""• tôi tò mò về neural network\n• tôi nghịch code Python suốt sáng\n• tôi lên kế hoạch đi Đà Lạt\n• tôi dọn dẹp file trên desktop\n• tôi research thị trường chứng khoán\n• tôi nhận ra mình cần nghỉ ngơi"""
|
| 145 |
+
], inputs=input_text)
|
| 146 |
+
gr.Markdown("""
|
| 147 |
+
### 🔑 Highly Recommend Keywords
|
| 148 |
+
Hệ thống nhận diện tốt nhất khi chứa các từ khóa sau:
|
| 149 |
+
- **Learning**: `tò mò, hiểu ra, nắm được, học được, khám phá`
|
| 150 |
+
- **Practice**: `code, debug, fix bug, thực hành, làm bài tập`
|
| 151 |
+
- **Planning**: `lên kế hoạch, đặt mục tiêu, roadmap, chiến lược`
|
| 152 |
+
- **Organization**: `dọn dẹp, sắp xếp folder, tổ chức file, setup`
|
| 153 |
+
- **Research**: `research, khảo sát, phân tích sâu, so sánh giải pháp`
|
| 154 |
+
- **Reflection**: `nhận ra, ý thức được, đánh giá bản thân, journaling`
|
| 155 |
+
""")
|
| 156 |
+
|
| 157 |
+
# CỘT GIỮA: Biểu đồ Donut
|
| 158 |
+
with gr.Column(scale=1):
|
| 159 |
+
chart_output = gr.Plot(label="📊 Daily Activity Distribution")
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
# CỘT PHẢI: Cảm xúc + API + Hướng dẫn
|
| 162 |
+
with gr.Column(scale=1):
|
| 163 |
+
sentiment_output = gr.Plot(label="🧠 Phân Tích Cảm Xúc (%)")
|
| 164 |
+
api_key_input = gr.Textbox(label="🔑 Groq API Key", type="password", info="Chỉ dùng để gọi AI trong phiên làm việc hiện tại. Không lưu trữ.")
|
| 165 |
+
gr.Markdown("""
|
| 166 |
+
### 📖 Hướng dẫn lấy API & ⚠️ Lưu ý bảo mật
|
| 167 |
+
1. Truy cập [console.groq.com/keys](https://console.groq.com/keys)
|
| 168 |
+
2. Đăng nhập bằng GitHub/Google → Nhấn **Create API Key** → Copy.
|
| 169 |
+
3. Dán vào ô trên và nhấn **Phân tích**.
|
| 170 |
+
> 🔒 **TUYỆT ĐỐI KHÔNG SHARE API KEY**: Theo quy định bảo mật & GDPR, API Key là chìa khóa truy cập tài khoản cá nhân. Việc lộ key có thể dẫn đến bị trừ quota, hack tài khoản hoặc vi phạm điều khoản dịch vụ. Code này chỉ gửi key đến server Groq trong request và không lưu lại anywhere.
|
| 171 |
+
""")
|
| 172 |
+
|
| 173 |
+
# DÒNG DƯỚI: Detailed Classification (Full width)
|
| 174 |
+
with gr.Row():
|
| 175 |
+
summary_output = gr.HTML(label="📋 Detailed Classification")
|
| 176 |
+
|
| 177 |
+
btn.click(fn=ai_agent.process, inputs=[input_text, api_key_input], outputs=[chart_output, sentiment_output, summary_output])
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
demo.launch(share=False)
|