File size: 12,135 Bytes
74b9bb1
 
d73e2cf
74b9bb1
0d9bba4
d73e2cf
 
 
 
 
 
 
 
74b9bb1
75afca8
d73e2cf
 
 
 
 
 
 
 
 
0d9bba4
d73e2cf
1fb7be3
 
516cc59
1fb7be3
75afca8
 
d73e2cf
 
 
da47594
 
0d9bba4
d73e2cf
 
b5061a3
d73e2cf
b5061a3
 
 
0d9bba4
d73e2cf
0d9bba4
d73e2cf
1fb7be3
d73e2cf
 
da47594
be06db1
d73e2cf
da47594
 
d73e2cf
 
 
 
 
 
 
da47594
 
d73e2cf
 
 
 
be06db1
d73e2cf
be06db1
d73e2cf
da47594
d73e2cf
 
da47594
 
 
d73e2cf
 
 
da47594
 
 
 
d73e2cf
da47594
 
 
 
 
 
 
d73e2cf
da47594
 
 
d73e2cf
157f214
da47594
 
d73e2cf
 
da47594
 
 
 
 
 
 
d73e2cf
 
da47594
 
 
 
 
 
 
1fb7be3
da47594
 
 
 
3280e8b
da47594
 
 
f1e3406
da47594
 
157f214
da47594
157f214
 
 
c1caa6e
da47594
d73e2cf
 
 
 
da47594
 
 
 
 
 
 
 
 
 
 
157f214
be06db1
 
da47594
 
 
 
 
1fb7be3
 
0d9bba4
da47594
 
 
d73e2cf
da47594
 
0d9bba4
d73e2cf
 
 
da47594
 
1fb7be3
d73e2cf
 
 
 
 
 
 
75afca8
d73e2cf
 
157f214
da47594
d73e2cf
 
da47594
 
d73e2cf
da47594
d73e2cf
 
 
 
0d9bba4
157f214
74b9bb1
 
be06db1
74b9bb1
be06db1
d73e2cf
 
 
 
 
 
 
be06db1
 
 
 
 
 
d73e2cf
 
be06db1
157f214
 
d73e2cf
157f214
be06db1
0d9bba4
be06db1
d73e2cf
 
be06db1
d73e2cf
157f214
d73e2cf
be06db1
d73e2cf
be06db1
d73e2cf
 
be06db1
d73e2cf
157f214
d73e2cf
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import gradio as gr
import plotly.graph_objects as go
import plotly.express as px
import re
import json
from collections import Counter

# Kiểm tra thư viện Groq
try:
    from groq import Groq
    GROQ_AVAILABLE = True
except ImportError:
    GROQ_AVAILABLE = False

class TaskDashboardAI_Vietnamese:
    def __init__(self):
        self.categories = ["Learning", "Practice", "Planning", "Organization", "Research", "Reflection"]
        self.priority_keywords = {
            "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"]},
            "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ử"]},
            "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"]},
            "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"]},
            "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"]},
            "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ý"]}
        }
        self.sentiment_labels = ["Quyết tâm", "Bối rối", "Buồn", "Sợ hãi", "Chiêm nghiệm", "Tự ti", "Khác"]

    def clean_text(self, text):
        return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip()

    def extract_tasks(self, text):
        lines = text.strip().split('\n')
        return [self.clean_text(line) for line in lines if self.clean_text(line) and len(self.clean_text(line)) > 4]

    def _call_groq_llm(self, prompt, api_key):
        if not GROQ_AVAILABLE or not api_key: 
            return None
        try:
            client = Groq(api_key=api_key)
            response = client.chat.completions.create(
                model="llama-3.3-70b-versatile", 
                messages=[{"role": "user", "content": prompt}],
                temperature=0.15, 
                max_tokens=600,
                top_p=0.9
            )
            return response.choices[0].message.content
        except Exception as e:
            return f"⚠️ Lỗi Groq: {str(e)}"

    def classify_task(self, task, api_key):
        task_lower = task.lower()
        
        # 1. Quét Strong Keywords
        for cat, keys in self.priority_keywords.items():
            if any(word in task_lower for word in keys["strong"]): 
                return cat
            
        # 2. Tính điểm Common Keywords
        scores = {cat: 0 for cat in self.categories}
        found_common = False
        for cat, keys in self.priority_keywords.items():
            for word in keys["common"]:
                if word in task_lower:
                    scores[cat] += 1
                    found_common = True
                    
        if found_common and max(scores.values()) >= 2:
            return max(scores, key=scores.get)
            
        # 3. Fallback Llama 3
        if api_key and GROQ_AVAILABLE:
            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 duy nhất. Hoạt động: '{task}'"
            res = self._call_groq_llm(prompt, api_key)
            if res and not res.startswith("⚠️"):
                clean_res = res.replace("```json", "").replace("```", "").strip()
                for cat in self.categories:
                    if cat.lower() in clean_res.lower(): 
                        return cat
        
        return max(scores, key=scores.get) if found_common else "Other"

    def analyze_sentiment(self, text, api_key):
        if not api_key or not GROQ_AVAILABLE: 
            return {k: 0 for k in self.sentiment_labels}
        
        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 bên dưới, KHÔNG thêm bất kỳ text nào khác:
{{
  "Quyết tâm": số_phần_trăm, 
  "Bối rối": số_phần_trăm, 
  "Buồn": số_phần_trăm, 
  "Sợ hãi": số_phần_trăm, 
  "Chiêm nghiệm": số_phần_trăm, 
  "Tự ti": số_phần_trăm, 
  "Khác": số_phần_trăm
}}
Tổng các số phải bằng 100.
Văn bản cần phân tích: {text}"""
        
        res = self._call_groq_llm(prompt, api_key)
        if not res or res.startswith("⚠️"): 
            return {k: 0 for k in self.sentiment_labels}
        
        try:
            match = re.search(r'\{.*\}', res, re.DOTALL)
            if match:
                data = json.loads(match.group(0))
                return {k: data.get(k, 0) for k in self.sentiment_labels}
        except: 
            pass
            
        return {k: 0 for k in self.sentiment_labels}

    def create_donut_chart(self, cat_counts):
        if not cat_counts: 
            fig = go.Figure()
            fig.add_annotation(text="Chưa có dữ liệu", showarrow=False)
            return fig
        
        labels = list(cat_counts.keys())
        values = list(cat_counts.values())
        colors = px.colors.qualitative.Pastel
        
        fig = go.Figure(data=[go.Pie(
            labels=labels,
            values=values,
            hole=0.2,
            marker_colors=colors,
            textinfo='percent+label',
            insidetextorientation='radial',
            textfont=dict(size=9, color="#333")  # Thu nhỏ chữ bên trong
        )])
        
        # --- SỬA TRIỆT ĐỂ: BỎ TITLE CỦA PLOTLY, CHỈ GIỮ LEGEND GỌN GÀNG ---
        fig.update_layout(
            # KHÔNG CÓ title ở đây nữa! Tiêu đề sẽ do Gradio Markdown đảm nhận
            height=500, # Tăng chiều cao để legend thoải mái
            margin=dict(t=20, b=100, l=20, r=20), # Bottom margin lớn (100) để chứa legend bên dưới
            showlegend=False,
        )
        return fig

    def create_sentiment_chart(self, sentiment_data):
        fig = go.Figure()
        colors = ["#a6cee3","#fb9a99","#b2df8a","#fdbf6f","#cab2d6","#ffff99","#cccccc"]
        fig.add_trace(go.Bar(
            x=list(sentiment_data.values()), 
            y=list(sentiment_data.keys()), 
            orientation='h', 
            marker_color=colors, 
            text=[f"{v}%" for v in sentiment_data.values()], 
            textposition='outside',
            hoverinfo='skip'
        ))
        fig.update_layout(
            title="🧠 Phân Tích Cảm Xúc (%)",
            xaxis=dict(range=[0, 105], title="", showgrid=False),
            yaxis=dict(title="", autorange="reversed"),
            margin=dict(l=100, r=30, t=50, b=50),
            height=380,
            bargap=0.3,
            font=dict(size=10)
        )
        return fig

    def process(self, text, api_key):
        if not text or not text.strip(): 
            return None, None, "⚠️ Vui lòng nhập hoạt động trước."
        
        tasks = self.extract_tasks(text)
        if not tasks: 
            return None, None, "❌ Không tìm thấy task hợp lệ (cần >4 ký tự)."

        results, cat_counter = [], Counter()
        for t in tasks:
            cat = self.classify_task(t, api_key)
            results.append((t, cat))
            cat_counter[cat] += 1

        chart = self.create_donut_chart(dict(cat_counter))
        sentiment = self.analyze_sentiment(text, api_key)
        sentiment_chart = self.create_sentiment_chart(sentiment)

        # HTML Detailed Classification
        color_map = {"Learning":"#a6cee3","Practice":"#fb9a99","Planning":"#b2df8a","Organization":"#fdbf6f","Research":"#cab2d6","Reflection":"#ffff99","Other":"#cccccc"}
        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;'>"
        for task, cat in results:
            bg = color_map.get(cat, "#eee")
            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>'
        html += "</ul><h3 style='border-bottom:2px solid #eee;padding-bottom:10px;margin-top:20px;'>📈 Summary</h3><ul>"
        
        total = sum(cat_counter.values())
        for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
            pct = (count/total)*100 if total > 0 else 0
            html += f'<li style="padding:5px 0;"><b>{cat}</b>: {count} tasks ({pct:.1f}%)</li>'
        html += "</ul></div>"
        
        return chart, sentiment_chart, html

ai_agent = TaskDashboardAI_Vietnamese()

with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
    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)`")
    
    with gr.Row():
        # CỘT TRÁI
        with gr.Column(scale=1):
            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...", elem_id="input_box")
            btn = gr.Button("🚀 Phân tích & Cảm xúc", variant="primary", size="lg")
            gr.Examples(examples=[
                """• 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"""
            ], inputs=input_text)
            gr.Markdown("""
### 🔑 Highly Recommend Keywords
Hệ thống nhận diện tốt nhất khi chứa các từ khóa sau:
- **Learning**: `tò mò, hiểu ra, nắm được, học được`
- **Practice**: `code, debug, fix bug, thực hành`
- **Planning**: `lên kế hoạch, đặt mục tiêu, roadmap`
- **Organization**: `dọn dẹp, sắp xếp folder, tổ chức file`
- **Research**: `research, khảo sát, phân tích sâu`
- **Reflection**: `nhận ra, ý thức được, đánh giá bản thân`
            """)

        # CỘT GIỮA - BIỂU ĐỒ DONUT
        # MẸO QUAN TRỌNG: Đặt tiêu đề bằng gr.Markdown NGAY TRÊN gr.Plot
        # Và KHÔNG dùng label trong gr.Plot để tránh đúp chữ
        with gr.Column(scale=1):
            gr.Markdown("### 📊 Daily Activity Distribution")
            chart_output = gr.Plot() 
            
        # CỘT PHẢI
        with gr.Column(scale=1):
            sentiment_output = gr.Plot(label="🧠 Phân Tích Cảm Xúc (%)")
            api_key_input = gr.Textbox(label="🔑 Groq API Key", type="password", info="Key không được lưu trữ.")
            gr.Markdown("""
### 📖 Hướng dẫn lấy API & ⚠️ Bảo mật
1. Truy cập [console.groq.com/keys](https://console.groq.com/keys)
2. Đăng nhập → Nhấn **Create API Key** → Copy.
3. Dán vào ô trên và nhấn **Phân tích**.
> 🔒 **KHÔNG SHARE API KEY**: Key là chìa khóa tài khoản cá nhân. Code chỉ gửi key đến Groq trong request và không lưu lại.
            """)

    # DÒNG DƯỚI
    with gr.Row():
        summary_output = gr.HTML(label=" Detailed Classification")

    btn.click(fn=ai_agent.process, inputs=[input_text, api_key_input], outputs=[chart_output, sentiment_output, summary_output])

if __name__ == "__main__":
    demo.launch(share=False)