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 = "

📋 Detailed Classification

📈 Summary

" 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)