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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -30
app.py CHANGED
@@ -33,13 +33,16 @@ class TaskDashboardAI_Vietnamese:
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:
@@ -47,9 +50,11 @@ class TaskDashboardAI_Vietnamese:
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}
@@ -57,61 +62,139 @@ class TaskDashboardAI_Vietnamese:
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.99, 'x':0.5, 'xanchor':'center', 'yanchor':'top'}, height=420, margin=dict(t=30, 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)
@@ -124,10 +207,13 @@ Văn bản: {text}"""
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()
 
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:
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}],
44
+ temperature=0.2,
45
+ max_tokens=400
46
  )
47
  return response.choices[0].message.content
48
  except Exception as e:
 
50
 
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
58
 
59
  # 2. Tính điểm Common Keywords
60
  scores = {cat: 0 for cat in self.categories}
 
62
  for cat, keys in self.priority_keywords.items():
63
  for word in keys["common"]:
64
  if word in task_lower:
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()
78
  for cat in self.categories:
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):
86
+ if not api_key or not GROQ_AVAILABLE:
87
+ return {k: 0 for k in self.sentiment_labels}
88
+
89
+ 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:
90
  {{
91
+ "Quyết tâm": số_phần_trăm,
92
+ "Bối rối": số_phần_trăm,
93
+ "Buồn": số_phần_trăm,
94
+ "Sợ hãi": số_phần_trăm,
95
+ "Chiêm nghiệm": số_phần_trăm,
96
+ "Tự ti": số_phần_trăm,
97
+ "Khác": số_phần_trăm
98
  }}
99
+ 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))
111
+ return {k: data.get(k, 0) for k in self.sentiment_labels}
112
+ except:
113
+ pass
114
+
115
+ return {k: 0 for k in self.sentiment_labels}
116
 
117
  def create_donut_chart(self, cat_counts):
118
+ if not cat_counts:
119
+ fig = go.Figure()
120
+ fig.add_annotation(text="Chưa có dữ liệu", showarrow=False)
121
+ return fig
122
+
123
+ labels = list(cat_counts.keys())
124
+ values = list(cat_counts.values())
125
  colors = px.colors.qualitative.Pastel
126
+
127
+ fig = go.Figure(data=[go.Pie(
128
+ labels=labels,
129
+ values=values,
130
+ hole=0.4,
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
+ )
159
+ )
160
  return fig
161
 
162
  def create_sentiment_chart(self, sentiment_data):
163
  fig = go.Figure()
164
+ colors = ["#a6cee3","#fb9a99","#b2df8a","#fdbf6f","#cab2d6","#ffff99","#cccccc"]
165
+ fig.add_trace(go.Bar(
166
+ x=list(sentiment_data.values()),
167
+ y=list(sentiment_data.keys()),
168
+ orientation='h',
169
+ marker_color=colors,
170
+ text=[f"{v}%" for v in sentiment_data.values()],
171
+ textposition='outside',
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,
181
+ font=dict(size=10)
182
+ )
183
  return fig
184
 
185
  def process(self, text, api_key):
186
+ if not text or not text.strip():
187
+ return None, None, "⚠️ Vui lòng nhập hoạt động trước."
188
+
189
  tasks = self.extract_tasks(text)
190
+ if not tasks:
191
+ return None, None, "❌ Không tìm thấy task hợp lệ (cần >4 ký tự)."
192
 
193
  results, cat_counter = [], Counter()
194
  for t in tasks:
195
  cat = self.classify_task(t, api_key)
196
+ results.append((t, cat))
197
+ cat_counter[cat] += 1
198
 
199
  chart = self.create_donut_chart(dict(cat_counter))
200
  sentiment = self.analyze_sentiment(text, api_key)
 
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):
213
+ pct = (count/total)*100 if total > 0 else 0
214
+ html += f'<li style="padding:5px 0;"><b>{cat}</b>: {count} tasks ({pct:.1f}%)</li>'
215
  html += "</ul></div>"
216
+
217
  return chart, sentiment_chart, html
218
 
219
  ai_agent = TaskDashboardAI_Vietnamese()