AugustinHuang commited on
Commit
d73e2cf
·
verified ·
1 Parent(s): 0d9bba4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -198
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 groq import Groq
 
 
 
 
 
 
 
7
 
8
  class TaskDashboardAI_Vietnamese:
9
- def __init__(self, groq_api_key):
10
- self.client = Groq(api_key=groq_api_key)
11
- self.model = "llama-3.1-8b-instant" # Dùng Llama 3.1 8B cho nhanh và chuẩn
12
-
13
- self.categories = [
14
- "Learning", "Practice", "Planning",
15
- "Organization", "Research", "Reflection", "Other"
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
- tasks = []
59
- for line in lines:
60
- cleaned = self.clean_text(line)
61
- if cleaned and len(cleaned) > 4:
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
- chat_completion = self.client.chat.completions.create(
71
- messages=[
72
- {"role": "system", "content": self.system_prompt},
73
- {"role": "user", "content": user_prompt}
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 json.loads(chat_completion.choices[0].message.content)
80
  except Exception as e:
81
- print(f"Lỗi API: {e}")
82
- return None
83
 
84
- def create_donut_chart(self, cat_counter):
85
- if not cat_counter:
86
- fig = go.Figure()
87
- fig.add_annotation(text="No data", showarrow=False)
88
- return fig
89
-
90
- labels = list(cat_counter.keys())
91
- values = list(cat_counter.values())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  colors = px.colors.qualitative.Pastel
93
-
94
- fig = go.Figure(data=[go.Pie(
95
- labels=labels, values=values, hole=0.5,
96
- marker_colors=colors, textinfo='percent+label',
97
- insidetextorientation='radial'
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 api_key or not api_key.strip():
110
- return None, "⚠️ Vui lòng nhập Groq API Key.", ""
111
- if not text or not text.strip():
112
- return None, "⚠️ Vui lòng nhập hoạt động.", ""
113
 
114
- # Cập nhật API Key nếu người dùng nhập mới
115
- self.client = Groq(api_key=api_key)
 
 
116
 
117
- tasks = self.extract_tasks(text)
118
- if not tasks:
119
- return None, "❌ Không tìm thấy task hợp lệ.", ""
120
-
121
- # Gọi LLM
122
- llm_result = self.analyze_with_llm(tasks)
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
- bg_color = color_map.get(cat, "#eeeeee")
149
- detail_html += f"""
150
- <li style="margin-bottom: 6px; padding: 8px; background-color: #fff; border-left: 5px solid {bg_color}; box-shadow: 0 1px 2px rgba(0,0,0,0.05); border-radius: 4px;">
151
- <span style="font-weight:bold; color:#555; font-size: 0.8em; text-transform:uppercase;">[{cat}]</span>
152
- <span style="color:#333; margin-left: 8px;">{task}</span>
153
- </li>"""
154
- detail_html += "</ul></div>"
155
-
156
- # 2. Tạo HTML Emotion Analysis (Phần bên phải)
157
- emotion_data = llm_result.get("emotion", {})
158
- emotion_label = emotion_data.get("label", "Không xác định")
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
- label="📝 Nhập hoạt động hàng ngày",
191
- placeholder="Ví dụ:\n• 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...",
192
- lines=20
193
- )
194
- btn = gr.Button("🚀 Phân tích bằng Llama 3", variant="primary", size="lg")
195
-
196
- gr.Examples(
197
- examples=[
198
- """• Hôm nay tôi tò mò về cách hoạt động của neural network nên đã xem mấy video explainer
199
- • Buổi sáng tôi nghịch code Python làm cái web scraper, bị bug mất 2 tiếng mới fix được
200
- • Tôi nhận ra mình quản lý thời gian quá kém, dạo này hay bị lẩn thẩn
201
- • Chiều tôi dọn dẹp lại toàn bộ folder trên Desktop cho dễ tìm
202
- • Tối tôi lên kế hoạch chi tiết cho dự án sắp tới""",
203
- ],
204
- inputs=input_text
205
- )
206
-
207
- # CỘT PHẢI: Chia làm 2 hàng ngang
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
- # HÀNG 2: Chia làm 2 cột nhỏ (Detailed bên trái, Emotion bên phải)
213
- with gr.Row():
214
- with gr.Column(scale=1):
215
- detail_output = gr.HTML(label="📋 Detailed Classification")
216
-
217
- with gr.Column(scale=1):
218
- emotion_output = gr.HTML(label="💡 Cảm xúc")
219
-
220
- # Sự kiện bấm nút
221
- btn.click(
222
- fn=TaskDashboardAI_Vietnamese(api_key="temp").process,
223
- inputs=[input_text, api_key_input],
224
- outputs=[chart_output, detail_output, emotion_output]
225
- )
226
-
227
- demo.launch()
 
 
 
 
 
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)