AugustinHuang commited on
Commit
be06db1
·
verified ·
1 Parent(s): da47594

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -36
app.py CHANGED
@@ -37,7 +37,6 @@ class TaskDashboardAI_Vietnamese:
37
  return None
38
  try:
39
  client = Groq(api_key=api_key)
40
- # Sử dụng model Llama 3.1 8b để nhanh và tiết kiệm, hoặc đổi thành llama-3.3-70b-versatile nếu cần thông minh hơn
41
  response = client.chat.completions.create(
42
  model="llama-3.1-8b-instant",
43
  messages=[{"role": "user", "content": prompt}],
@@ -51,7 +50,7 @@ class TaskDashboardAI_Vietnamese:
51
  def classify_task(self, task, api_key):
52
  task_lower = task.lower()
53
 
54
- # 1. Quét Strong Keywords (Ưu tiên tuyệt đối)
55
  for cat, keys in self.priority_keywords.items():
56
  if any(word in task_lower for word in keys["strong"]):
57
  return cat
@@ -65,13 +64,12 @@ class TaskDashboardAI_Vietnamese:
65
  scores[cat] += 1
66
  found_common = True
67
 
68
- # Nếu điểm common cao (>=2 từ khớp) -> Tin tưởng Python
69
  if found_common and max(scores.values()) >= 2:
70
  return max(scores, key=scores.get)
71
 
72
- # 3. Fallback Llama 3 (Chỉ gọi khi Python chưa rõ ràng)
73
  if api_key and GROQ_AVAILABLE:
74
- 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, không giải thích. Hoạt động: '{task}'"
75
  res = self._call_groq_llm(prompt, api_key)
76
  if res and not res.startswith("⚠️"):
77
  clean_res = res.replace("```json", "").replace("```", "").strip()
@@ -79,7 +77,6 @@ class TaskDashboardAI_Vietnamese:
79
  if cat.lower() in clean_res.lower():
80
  return cat
81
 
82
- # Default fallback
83
  return max(scores, key=scores.get) if found_common else "Other"
84
 
85
  def analyze_sentiment(self, text, api_key):
@@ -100,11 +97,10 @@ Tổng các số phải bằng 100.
100
  Văn bản cần phân tích: {text}"""
101
 
102
  res = self._call_groq_llm(prompt, api_key)
103
- if not res or res.startswith("⚠️"):
104
  return {k: 0 for k in self.sentiment_labels}
105
 
106
  try:
107
- # Trích xuất JSON an toàn từ phản hồi của LLM
108
  match = re.search(r'\{.*\}', res, re.DOTALL)
109
  if match:
110
  data = json.loads(match.group(0))
@@ -131,28 +127,31 @@ Văn bản cần phân tích: {text}"""
131
  marker_colors=colors,
132
  textinfo='percent+label',
133
  insidetextorientation='radial',
134
- textfont=dict(size=10) # Chữ bên trong bánh nhỏ lại
135
  )])
136
 
 
137
  fig.update_layout(
 
 
138
  title={
139
  'text': "📊 Daily Activity Distribution",
140
- 'y': 0.98, # Xích tiêu đề lên sát mép
141
  'x': 0.5,
142
  'xanchor': 'center',
143
  'yanchor': 'top',
144
- 'font': dict(size=16)
145
  },
146
- height=420,
147
- margin=dict(t=30, b=20, l=20, r=20), # Giảm padding top/bottom
148
  showlegend=True,
149
  legend=dict(
150
  orientation="h",
151
  yanchor="bottom",
152
- y=-0.05, # Kéo legend sát vào bánh đồ hơn
153
  xanchor="center",
154
  x=0.5,
155
- font=dict(size=9), # <--- Làm chữ chú thích nhỏ và gọn hơn
156
  bgcolor="rgba(0,0,0,0)",
157
  traceorder="grouped"
158
  )
@@ -172,9 +171,9 @@ Văn bản cần phân tích: {text}"""
172
  hoverinfo='skip'
173
  ))
174
  fig.update_layout(
175
- title="🧠 Phân Tích Cảm Xúc (%)",
176
- xaxis=dict(range=[0, 105], title="Phần trăm (%)", showgrid=False),
177
- yaxis=dict(title="", autorange="reversed"), # Đảo ngược để cảm xúc mạnh nhất lên đầu
178
  margin=dict(l=100, r=30, t=50, b=50),
179
  height=380,
180
  bargap=0.3,
@@ -206,7 +205,7 @@ Văn bản cần phân tích: {text}"""
206
  for task, cat in results:
207
  bg = color_map.get(cat, "#eee")
208
  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>'
209
- html += "</ul><h3 style='border-bottom:2px solid #eee;padding-bottom:10px;margin-top:20px;'>📈 Summary</h3><ul>"
210
 
211
  total = sum(cat_counter.values())
212
  for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
@@ -219,12 +218,12 @@ Văn bản cần phân tích: {text}"""
219
  ai_agent = TaskDashboardAI_Vietnamese()
220
 
221
  with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
222
- 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.`")
223
 
224
  with gr.Row():
225
- # CỘT TRÁI: Nhập liệu + Gợi ý
226
  with gr.Column(scale=1):
227
- 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")
228
  btn = gr.Button("🚀 Phân tích & Cảm xúc", variant="primary", size="lg")
229
  gr.Examples(examples=[
230
  """• 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"""
@@ -232,31 +231,32 @@ with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as
232
  gr.Markdown("""
233
  ### 🔑 Highly Recommend Keywords
234
  Hệ thống nhận diện tốt nhất khi chứa các từ khóa sau:
235
- - **Learning**: `tò mò, hiểu ra, nắm được, học được, khám phá`
236
- - **Practice**: `code, debug, fix bug, thực hành, làm bài tập`
237
- - **Planning**: `lên kế hoạch, đặt mục tiêu, roadmap, chiến lược`
238
- - **Organization**: `dọn dẹp, sắp xếp folder, tổ chức file, setup`
239
- - **Research**: `research, khảo sát, phân tích sâu, so sánh giải pháp`
240
- - **Reflection**: `nhận ra, ý thức được, đánh giá bản thân, journaling`
241
  """)
242
 
243
- # CỘT GIỮA: Biểu đồ Donut
 
244
  with gr.Column(scale=1):
245
- chart_output = gr.Plot(label="📊 Daily Activity Distribution")
246
 
247
- # CỘT PHẢI: Cảm xúc + API + Hướng dẫn
248
  with gr.Column(scale=1):
249
  sentiment_output = gr.Plot(label="🧠 Phân Tích Cảm Xúc (%)")
250
- 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ữ.")
251
  gr.Markdown("""
252
- ### 📖 Hướng dẫn lấy API & ⚠️ Lưu ý bảo mật
253
  1. Truy cập [console.groq.com/keys](https://console.groq.com/keys)
254
- 2. Đăng nhập bằng GitHub/Google → Nhấn **Create API Key** → Copy.
255
  3. Dán vào ô trên và nhấn **Phân tích**.
256
- > 🔒 **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.
257
  """)
258
 
259
- # DÒNG DƯỚI: Detailed Classification (Full width)
260
  with gr.Row():
261
  summary_output = gr.HTML(label="📋 Detailed Classification")
262
 
 
37
  return None
38
  try:
39
  client = Groq(api_key=api_key)
 
40
  response = client.chat.completions.create(
41
  model="llama-3.1-8b-instant",
42
  messages=[{"role": "user", "content": prompt}],
 
50
  def classify_task(self, task, api_key):
51
  task_lower = task.lower()
52
 
53
+ # 1. Quét Strong Keywords
54
  for cat, keys in self.priority_keywords.items():
55
  if any(word in task_lower for word in keys["strong"]):
56
  return cat
 
64
  scores[cat] += 1
65
  found_common = True
66
 
 
67
  if found_common and max(scores.values()) >= 2:
68
  return max(scores, key=scores.get)
69
 
70
+ # 3. Fallback Llama 3
71
  if api_key and GROQ_AVAILABLE:
72
+ 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}'"
73
  res = self._call_groq_llm(prompt, api_key)
74
  if res and not res.startswith("⚠️"):
75
  clean_res = res.replace("```json", "").replace("```", "").strip()
 
77
  if cat.lower() in clean_res.lower():
78
  return cat
79
 
 
80
  return max(scores, key=scores.get) if found_common else "Other"
81
 
82
  def analyze_sentiment(self, text, api_key):
 
97
  Văn bản cần phân tích: {text}"""
98
 
99
  res = self._call_groq_llm(prompt, api_key)
100
+ if not res or res.startswith("️"):
101
  return {k: 0 for k in self.sentiment_labels}
102
 
103
  try:
 
104
  match = re.search(r'\{.*\}', res, re.DOTALL)
105
  if match:
106
  data = json.loads(match.group(0))
 
127
  marker_colors=colors,
128
  textinfo='percent+label',
129
  insidetextorientation='radial',
130
+ textfont=dict(size=11, color="#333") # Chữ bên trong rõ hơn chút
131
  )])
132
 
133
+ # --- PHẦN SỬA LI GIAO DIỆN Ở ĐÂY ---
134
  fig.update_layout(
135
+ # Bỏ title ở đây nếu muốn dùng label của Gradio, HOẶC giữ title này và bỏ label Gradio
136
+ # Ở đây mình giữ title của Plotly vì nó đẹp và căn chỉnh dễ hơn
137
  title={
138
  'text': "📊 Daily Activity Distribution",
139
+ 'y': 0.95,
140
  'x': 0.5,
141
  'xanchor': 'center',
142
  'yanchor': 'top',
143
+ 'font': dict(size=18, color="#444")
144
  },
145
+ height=480, # Tăng chiều cao để legend không bị đè
146
+ margin=dict(t=60, b=80, l=20, r=20), # Tăng bottom margin (b=80) để chứa legend
147
  showlegend=True,
148
  legend=dict(
149
  orientation="h",
150
  yanchor="bottom",
151
+ y=-0.15, # Đẩy legend xuống dưới hẳn, tránh chồng lên bánh
152
  xanchor="center",
153
  x=0.5,
154
+ font=dict(size=10),
155
  bgcolor="rgba(0,0,0,0)",
156
  traceorder="grouped"
157
  )
 
171
  hoverinfo='skip'
172
  ))
173
  fig.update_layout(
174
+ title=" Phân Tích Cảm Xúc (%)",
175
+ xaxis=dict(range=[0, 105], title="", showgrid=False),
176
+ yaxis=dict(title="", autorange="reversed"),
177
  margin=dict(l=100, r=30, t=50, b=50),
178
  height=380,
179
  bargap=0.3,
 
205
  for task, cat in results:
206
  bg = color_map.get(cat, "#eee")
207
  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>'
208
+ html += "</ul><h3 style='border-bottom:2px solid #eee;padding-bottom:10px;margin-top:20px;'> Summary</h3><ul>"
209
 
210
  total = sum(cat_counter.values())
211
  for cat, count in sorted(cat_counter.items(), key=lambda x: x[1], reverse=True):
 
218
  ai_agent = TaskDashboardAI_Vietnamese()
219
 
220
  with gr.Blocks(title="Vietnamese Task Dashboard AI", theme=gr.themes.Soft()) as demo:
221
+ 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)`")
222
 
223
  with gr.Row():
224
+ # CỘT TRÁI
225
  with gr.Column(scale=1):
226
+ 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")
227
  btn = gr.Button("🚀 Phân tích & Cảm xúc", variant="primary", size="lg")
228
  gr.Examples(examples=[
229
  """• 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"""
 
231
  gr.Markdown("""
232
  ### 🔑 Highly Recommend Keywords
233
  Hệ thống nhận diện tốt nhất khi chứa các từ khóa sau:
234
+ - **Learning**: `tò mò, hiểu ra, nắm được, học được`
235
+ - **Practice**: `code, debug, fix bug, thực hành`
236
+ - **Planning**: `lên kế hoạch, đặt mục tiêu, roadmap`
237
+ - **Organization**: `dọn dẹp, sắp xếp folder, tổ chức file`
238
+ - **Research**: `research, khảo sát, phân tích sâu`
239
+ - **Reflection**: `nhận ra, ý thức được, đánh giá bản thân`
240
  """)
241
 
242
+ # CỘT GIỮA - BIỂU ĐỒ DONUT
243
+ # Lưu ý: Mình bỏ label="..." ở đây để tránh bị đúp tiêu đề với Plotly
244
  with gr.Column(scale=1):
245
+ chart_output = gr.Plot()
246
 
247
+ # CỘT PHẢI
248
  with gr.Column(scale=1):
249
  sentiment_output = gr.Plot(label="🧠 Phân Tích Cảm Xúc (%)")
250
+ api_key_input = gr.Textbox(label="🔑 Groq API Key", type="password", info="Key không được lưu trữ.")
251
  gr.Markdown("""
252
+ ### Hướng dẫn lấy API & ️ Bảo mật
253
  1. Truy cập [console.groq.com/keys](https://console.groq.com/keys)
254
+ 2. Đăng nhập → Nhấn **Create API Key** → Copy.
255
  3. Dán vào ô trên và nhấn **Phân tích**.
256
+ > 🔒 **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.
257
  """)
258
 
259
+ # DÒNG DƯỚI
260
  with gr.Row():
261
  summary_output = gr.HTML(label="📋 Detailed Classification")
262