File size: 7,243 Bytes
628dac3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py - Gradio App cho Hugging Face Spaces
import gradio as gr
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import re
from transformers import pipeline
import io
import base64

class TaskDashboardAI:
    def __init__(self):
        # Load AI models
        self.classifier = pipeline(
            "zero-shot-classification",
            model="facebook/bart-large-mnli"
        )
        
        # Categories mặc định
        self.default_categories = [
            "Learning", "Practice", "Planning/Ideas", 
            "Research", "Organization"
        ]
        
        # Keywords mapping
        self.category_keywords = {
            "Learning": ["học", "video", "xem", "tìm hiểu", "khám phá", "study", "learn"],
            "Practice": ["thực hành", "practice", "code", "nghịch", "thử", "làm"],
            "Planning/Ideas": ["dự định", "muốn", "sẽ", "plan", "chiến lược", "mvp", "tò mò"],
            "Organization": ["folder", "lưu trữ", "tạo", "setup", "organize", "quản lý"],
            "Research": ["nghiên cứu", "tìm hiểu", "research", "đọc", "phân tích"],
        }
    
    def extract_tasks_from_text(self, text):
        """Tách text thành từng task"""
        # Pattern: tìm các dòng bắt đầu bằng "•" hoặc số
        tasks = re.split(r'[•\-\*]|\n\d+\.', text)
        tasks = [t.strip() for t in tasks if t.strip() and len(t.strip()) > 10]
        return tasks
    
    def classify_task(self, task):
        """Dùng AI để phân loại task"""
        # Cách 1: Zero-shot classification
        result = self.classifier(
            task, 
            self.default_categories,
            multi_label=False
        )
        return result['labels'][0]
    
    def classify_task_keywords(self, task):
        """Phân loại bằng keywords (backup)"""
        task_lower = task.lower()
        scores = {}
        
        for category, keywords in self.category_keywords.items():
            score = sum(1 for kw in keywords if kw in task_lower)
            scores[category] = score
        
        return max(scores, key=scores.get) if max(scores.values()) > 0 else "Other"
    
    def determine_chart_type(self, data_dict):
        """AI quyết định loại biểu đồ phù hợp"""
        n_categories = len(data_dict)
        total_items = sum(data_dict.values())
        
        if n_categories <= 3:
            return "pie"
        elif n_categories <= 6:
            return "donut"
        elif n_categories <= 10:
            return "bar"
        else:
            return "horizontal_bar"
    
    def create_dashboard(self, tasks_with_categories):
        """Tạo dashboard thông minh"""
        # Đếm tasks theo category
        category_counts = {}
        for task, category in tasks_with_categories:
            category_counts[category] = category_counts.get(category, 0) + 1
        
        # Chọn chart type
        chart_type = self.determine_chart_type(category_counts)
        
        # Tạo figure
        categories = list(category_counts.keys())
        counts = list(category_counts.values())
        colors = px.colors.qualitative.Pastel
        
        if chart_type in ["pie", "donut"]:
            fig = go.Figure(data=[go.Pie(
                labels=categories,
                values=counts,
                hole=0.4 if chart_type == "donut" else 0,
                marker_colors=colors,
                textinfo='percent+label',
                insidetextorientation='radial'
            )])
            fig.update_layout(
                title_text="📊 Task Distribution by Category",
                height=600,
                showlegend=True
            )
        
        elif chart_type == "bar":
            fig = px.bar(
                x=categories,
                y=counts,
                color=categories,
                color_discrete_sequence=colors,
                title="📊 Task Distribution by Category"
            )
            fig.update_layout(
                height=600,
                showlegend=False,
                xaxis_title="Category",
                yaxis_title="Number of Tasks"
            )
        
        else:  # horizontal_bar
            fig = px.bar(
                y=categories,
                x=counts,
                orientation='h',
                color=categories,
                color_discrete_sequence=colors,
                title="📊 Task Distribution by Category"
            )
            fig.update_layout(
                height=600,
                showlegend=False
            )
        
        return fig, category_counts
    
    def process_text(self, text):
        """Xử lý text input và tạo dashboard"""
        # Extract tasks
        tasks = self.extract_tasks_from_text(text)
        
        # Classify từng task
        tasks_with_categories = []
        for task in tasks:
            # Dùng AI classification
            category = self.classify_task(task)
            tasks_with_categories.append((task, category))
        
        # Tạo dashboard
        fig, category_counts = self.create_dashboard(tasks_with_categories)
        
        # Tạo summary text
        summary = "📋 **Classification Results:**\n\n"
        for task, category in tasks_with_categories:
            summary += f"✓ **{category}**: {task[:50]}...\n"
        
        summary += f"\n📊 **Summary:**\n"
        for cat, count in category_counts.items():
            summary += f"• {cat}: {count} tasks\n"
        
        return fig, summary, tasks_with_categories

# Gradio Interface
dashboard_ai = TaskDashboardAI()

def create_dashboard_from_text(text):
    fig, summary, tasks = dashboard_ai.process_text(text)
    return fig, summary

# Tạo Gradio UI
with gr.Blocks(title="AI Task Dashboard Generator", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🤖 AI Task Dashboard Generator
    **Paste your daily tasks → AI classifies → Auto creates beautiful charts**
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            input_text = gr.Textbox(
                label="📝 Paste Your Tasks Here",
                placeholder="• tôi đã học Python\n• tôi đã thực hành web scraping\n...",
                lines=15
            )
            btn = gr.Button("🚀 Generate Dashboard", variant="primary")
        
        with gr.Column(scale=2):
            chart_output = gr.Plot(label="📊 Dashboard")
            summary_output = gr.Textbox(label="📋 Classification Summary", lines=10)
    
    btn.click(
        fn=create_dashboard_from_text,
        inputs=input_text,
        outputs=[chart_output, summary_output]
    )
    
    # Examples
    gr.Examples(
        examples=[
            """• tôi đã học Python cơ bản
            • tôi đã xem video về machine learning
            • tôi muốn tạo dashboard tự động
            • tôi đã thực hành web scraping
            • tôi cần organize folders
            • tôi sẽ nghiên cứu về AI agents""",
        ],
        inputs=input_text
    )

demo.launch()