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 SmartJournalAI: def __init__(self): # Các category cơ bản self.categories = [ "Learning 📚", "Practice 💻", "Planning 🗺️", "Organization 📂", "Research 🔍", "Reflection 🧘" ] # Từ khóa hỗ trợ phân loại offline (fallback) self.priority_keywords = { "Learning 📚": { "strong": ["tò mò", "hiểu ra", "nắm được", "biết thêm", "học được", "khám phá", "learn", "understand"], "common": ["học", "xem video", "đọc sách", "tutorial", "lý thuyết", "course"] }, "Practice 💻": { "strong": ["code", "viết code", "debug", "fix bug", "thực hành", "làm bài tập", "nghịch code", "build", "implement"], "common": ["làm", "thử", "xây dựng", "chạy thử", "practice", "coding"] }, "Planning 🗺️": { "strong": ["lên kế hoạch", "lập plan", "đặt mục tiêu", "roadmap", "chiến lược", "plan", "goal"], "common": ["muốn", "sẽ", "dự định", "target", "mong muốn", "schedule"] }, "Organization 📂": { "strong": ["dọn dẹp", "sắp xếp folder", "tổ chức file", "setup máy", "cấu trúc lại", "clean up", "organize"], "common": ["lưu", "tạo folder", "quản lý", "gọn gàng", "file management"] }, "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ỹ", "investigate"], "common": ["tìm hiểu", "tìm kiếm", "đọc tài liệu", "search", "explore"] }, "Reflection 🧘": { "strong": ["nhận ra", "ý thức được", "reflect", "đánh giá bản thân", "journaling", "realize", "mindfulness"], "common": ["suy nghĩ", "thấy rằng", "cảm thấy", "viết nhật ký", "thoughts"] } } def clean_text(self, text): """Làm sạch văn bản đầu vào""" return re.sub(r'^[•\-\*\d\.\)]+\s*', '', text).strip() def extract_tasks(self, text): """Tách các dòng thành task riêng biệt""" 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): """Gọi API Groq an toàn""" 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.3, max_tokens=800, top_p=0.9 ) return response.choices[0].message.content except Exception as e: return f"⚠️ Lỗi kết nối Groq: {str(e)}" def classify_task_offline(self, task): """Phân loại cơ bản dựa trên từ khóa (Fallback)""" 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()) >= 1: return max(scores, key=scores.get) return "Other 📝" def create_donut_chart(self, cat_counts): """Tạo biểu đồ Donut nhất quán và đẹp mắt""" if not cat_counts: fig = go.Figure() fig.add_annotation(text="Chưa có dữ liệu hoạt động", showarrow=False, font=dict(size=14)) fig.update_layout(height=300, margin=dict(t=0, b=0, l=0, r=0)) return fig labels = list(cat_counts.keys()) values = list(cat_counts.values()) # Màu sắc pastel dịu mắt colors = px.colors.qualitative.Pastel fig = go.Figure(data=[go.Pie( labels=labels, values=values, hole=0.4, marker_colors=colors, textinfo='percent+label', insidetextorientation='radial', textfont=dict(size=10, color="#444"), hoverinfo='label+percent+value' )]) fig.update_layout( showlegend=True, legend=dict( orientation="h", yanchor="bottom", y=-0.1, xanchor="center", x=0.5, font=dict(size=10) ), margin=dict(t=20, b=60, l=20, r=20), height=350, font=dict(family="Arial, sans-serif") ) return fig def generate_advice_and_classify(self, tasks, api_key): """ Hàm cốt lõi: Sử dụng LLM để phân loại chính xác VÀ đưa ra lời khuyên. """ tasks_list_str = "\n".join([f"- {t}" for t in tasks]) prompt = f""" Bạn là một người bạn đồng hành thông minh và ân cần. Nhiệm vụ của bạn là phân tích nhật ký hoạt động hàng ngày. Dữ liệu đầu vào: {tasks_list_str} YÊU CẦU: Hãy thực hiện 2 việc sau và trả về duy nhất một chuỗi JSON hợp lệ (KHÔNG kèm markdown code block như ```json): 1. PHÂN LOẠI CHI TIẾT: Xét từng task, gán nó vào một trong các nhóm: ["Learning 📚", "Practice 💻", "Planning 🗺️", "Organization 📂", "Research 🔍", "Reflection 🧘", "Other 📝"]. 2. LỜI KHUYÊN & AN ỦI (Advice): - Dựa vào sự phân bố hoạt động, hãy đưa ra một lời nhận xét ngắn gọn, ấm áp. - Ví dụ: Nếu học nhiều nhưng ít thực hành -> Khuyên áp dụng kiến thức. - QUAN TRỌNG: Hãy phát hiện ngôn ngữ người dùng (Tiếng Việt/Anh) và viết lời khuyên bằng CHÍNH NGÔN NGỮ ĐÓ. FORMAT JSON TRẢ VỀ: {{ "classified_tasks": [ {"task": "nội dung task gốc", "category": "Tên Category"} ], "advice": "Lời khuyên ấm áp, ngắn gọn." }} """ res = self._call_groq_llm(prompt, api_key) if not res or res.startswith("⚠️"): # Fallback nếu lỗi API fallback_results = [{"task": t, "category": self.classify_task_offline(t)} for t in tasks] return { "classified_tasks": fallback_results, "advice": "⚠️ Không thể kết nối AI để đưa ra lời khuyên chi tiết. Nhưng bạn đã làm rất tốt khi ghi chép lại ngày hôm nay!" } try: # Xử lý trường hợp LLM trả về markdown ```json ... ``` clean_res = res.replace("```json", "").replace("```", "").strip() data = json.loads(clean_res) return data except Exception as e: print(f"JSON Parse Error: {e}") # Fallback fallback_results = [{"task": t, "category": self.classify_task_offline(t)} for t in tasks] return { "classified_tasks": fallback_results, "advice": "Hệ thống gặp chút trục trặc khi phân tích sâu, nhưng biểu đồ bên dưới vẫn phản ánh đúng nỗ lực của bạn hôm nay." } def process(self, text, api_key): if not text or not text.strip(): return None, "⚠️ Vui lòng nhập hoạt động của bạn.", "" tasks = self.extract_tasks(text) if not tasks: return None, "❌ Không tìm thấy task hợp lệ (cần >4 ký tự).", "" has_api = bool(api_key and GROQ_AVAILABLE) if has_api: ai_result = self.generate_advice_and_classify(tasks, api_key) classified_tasks = ai_result.get("classified_tasks", []) advice_text = ai_result.get("advice", "") # Xây dựng lại Counter từ kết quả AI final_counter = Counter([item['category'] for item in classified_tasks]) else: # Chế độ Offline classified_tasks = [] final_counter = Counter() for t in tasks: cat = self.classify_task_offline(t) classified_tasks.append({"task": t, "category": cat}) final_counter[cat] += 1 advice_text = "💡 Mẹo: Nhập Groq API Key để nhận lời khuyên cá nhân hóa từ AI Llama-3 nhé!" # Vẽ biểu đồ chart = self.create_donut_chart(dict(final_counter)) # Tạo HTML chi tiết color_map = { "Learning 📚": "#a6cee3", "Practice 💻": "#fb9a99", "Planning 🗺️": "#b2df8a", "Organization 📂": "#fdbf6f", "Research 🔍": "#cab2d6", "Reflection 🧘": "#ffff99", "Other 📝": "#cccccc" } html_details = "
" for item in classified_tasks: bg = color_map.get(item['category'], "#eee") html_details += f'''
[{item['category']}] {item['task']}
''' html_details += "
" return chart, advice_text, html_details # Khởi tạo Agent ai_agent = SmartJournalAI() with gr.Blocks(title="Smart Journal AI", theme=gr.themes.Soft()) as demo: gr.Markdown("# 🇻🇳 Smart Journal AI\n*Người bạn đồng hành phân tích & an ủi qua nhật ký hàng ngày*") with gr.Row(): # CỘT TRÁI: INPUT with gr.Column(scale=1): input_text = gr.Textbox( label="📝 Hôm nay bạn đã làm gì?", lines=8, placeholder="Ví dụ:\n• Tôi tò mò về cách hoạt động của AI\n• Code thử một trang web nhỏ\n• Dọn dẹp desktop cho gọn gàng...", elem_id="input_box" ) btn = gr.Button("✨ Phân tích & Nhận lời khuyên", 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 cảm thấy hơi mệt vì làm việc quá nhiều", "• I spent 2 hours reading about quantum physics\n• I organized my photo library\n• I feel confused about my career path", "• Lên kế hoạch đi Đà Lạt cuối tuần\n• Research vé máy bay\n• Mua vali mới" ], inputs=input_text ) api_key_input = gr.Textbox( label="🔑 Groq API Key (Optional)", type="password", info="Để nhận lời khuyên thông minh từ Llama-3. Key không được lưu trữ." ) gr.Markdown(""" 🔒 Bảo mật: Key chỉ được dùng để gửi request đến Groq và không lưu lại trên server. """) # CỘT GIỮA: BIỂU ĐỒ with gr.Column(scale=1): gr.Markdown("### 📊 Cân bằng cuộc sống") chart_output = gr.Plot(label="Phân bổ hoạt động") # CỘT PHẢI: LỜI KHUYÊN & CHI TIẾT with gr.Column(scale=1): gr.Markdown("### 💬 Lời nhắn từ AI") advice_output = gr.Markdown( value="_Nhấn nút phân tích để nhận lời khuyên..._", elem_classes=["advice-box"] ) with gr.Accordion("📋 Chi tiết phân loại", open=False): summary_output = gr.HTML() # Style tùy chỉnh cho box lời khuyên gr.HTML(""" """) btn.click( fn=ai_agent.process, inputs=[input_text, api_key_input], outputs=[chart_output, advice_output, summary_output] ) if __name__ == "__main__": demo.launch(share=False)