tanish78 commited on
Commit
7dc663d
·
verified ·
1 Parent(s): b880e6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +498 -16
app.py CHANGED
@@ -10,23 +10,505 @@ import matplotlib.pyplot as plt
10
  import plotly.express as px
11
  from PIL import Image
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  categories_keywords = {
14
- 'Application Status': ['application', 'applied', 'update on my application', 'result of my application', 'selected', 'selection process', 'apply', 'fellow', 'lesson plan', 'status of my application', 'application update', 'application status', 'applied for'],
15
- 'Volunteering': ['volunteering', 'volunteer', 'volunteering certificate', 'resume my volunteering', 'volunteering journey', 'volunteering with TFI', 'volunteering opportunities', 'volunteer work', 'volunteer program'],
16
- 'Certificates': ['certificate', 'certificates', 'certificate of completion', 'volunteer certificate', 'issue certificate'],
17
- 'Job Opportunities': ['job', 'vacancy', 'Talent Acquisition Executive job', 'opportunity', 'job opening', 'job position', 'career opportunities'],
18
- 'Surveys and Forms': ['survey', 'form', 'fill out the survey', 'application form', 'survey link', 'survey form', 'form submission'],
19
- 'General Queries': ['query', 'queries', 'questions', 'feedback', 'loved', 'overwhelming', 'general question', 'inquiry', 'query about'],
20
- 'Spam': ['free recharge', 'offer', 'click the link', 'https'],
21
- 'Rescheduling and Postponing': ['reschedule', 'postpone', 'cancellation', 'date', 'time slot', 'change date', 'change time', 'reschedule appointment'],
22
- 'Contact and Communication Issues': ['call', 'phone', 'contact', 'not received', 'contact support', 'phone call', 'call back', 'internet'],
23
- 'Email and Credentials Issues': ['email', 'credentials', 'received', 'email issue', 'email problem', 'credential issue', 'login problem'],
24
- 'Timing and Scheduling': ['session', 'time', 'interview', 'baje', 'schedule time', 'meeting time', 'appointment time'],
25
- 'Salary and Benefits': ['salary', 'increment', 'accommodation', 'training period', 'reside', 'stipend', 'pay', 'wage', 'salary details', 'benefits information'],
26
- 'Technical Issues': ['network issues', 'zoom meeting', 'passcode', 'technical', 'issue','technical problem', 'system issue', 'technical support'],
27
- 'Complaint Handling': ['help', 'i need help', 'Help me', 'complaint', 'issue is unresolved', 'unsatisfied', 'bad experience'],
28
- 'End of Conversation': ['thanks', 'thankss', 'thank u', 'thank you', 'ok', 'okay', 'done', 'joining', 'sounds good', 'goodbye', 'end chat', 'end'],
29
- 'Miscellaneous': []
 
 
 
 
 
 
 
 
 
30
  }
31
 
32
 
 
10
  import plotly.express as px
11
  from PIL import Image
12
 
13
+
14
+ Can you take in a .csv file as an input to conduct data analysis?
15
+ ChatGPT
16
+ Yes, I can take in a .csv file and perform various types of data analysis on it. You can upload the .csv file, and let me know what specific analysis or processing you would like to perform.
17
+
18
+ import gradio as gr
19
+ import pandas as pd
20
+ from sklearn.feature_extraction.text import TfidfVectorizer
21
+ from sklearn.cluster import KMeans
22
+ import re
23
+ from io import BytesIO
24
+ import tempfile
25
+ from wordcloud import WordCloud, STOPWORDS
26
+ import matplotlib.pyplot as plt
27
+ import plotly.express as px
28
+ from PIL import Image
29
+
30
+ categories_keywords = {
31
+ "Application Status": ["application status", "application", "status", "submitted", "processing", "pending", "approval", "rejected", "accepted"],
32
+ "Volunteering": ["volunteer", "volunteering", "help out", "assist", "volunteer work", "volunteer opportunities"],
33
+ "Certificates": ["certificate", "certificates", "completion", "certification", "accreditation", "proof", "document", "certified"],
34
+ "Job Opportunities": ["job", "opportunity", "career", "vacancy", "position", "employment", "hiring", "recruitment", "internship"],
35
+ "Surveys and Forms": ["survey", "form", "forms", "questionnaire", "feedback form", "response", "fill out", "submission"],
36
+ "General Queries": ["hello", "hi", "help", "general", "query", "question", "info", "information", "inquiry", "ask"],
37
+ "Spam": ["spam", "subscribe", "remove", "stop", "junk", "block", "opt-out", "watch my video", "click on this link", "win prize"],
38
+ "Rescheduling and Postponing": ["reschedule", "postpone", "delay", "change date", "new time", "rearrange", "shift", "adjust timing"],
39
+ "Contact and Communication Issues": ["contact", "communicate", "communication", "reach out", "phone", "email", "address", "details"],
40
+ "Email and Credentials Issues": ["email", "credentials", "login", "password", "access", "username", "account", "verification", "reset"],
41
+ "Timing and Scheduling": ["timing", "schedule", "scheduling", "time", "appointment", "availability", "calendar", "book", "slot"],
42
+ "Salary and Benefits": ["salary", "benefits", "pay", "compensation", "wages", "earnings", "package", "remuneration", "incentives"],
43
+ "Technical Issues": ["technical", "issue", "problem", "error", "bug", "glitch", "fix", "troubleshoot", "support"],
44
+ "End of Conversation": ["bye", "thank you", "thanks", "goodbye", "see you", "later", "end", "close", "sign off"],
45
+ "Start of Conversation": ["start", "begin", "hello", "hi", "initiate", "greet", "greeting", "open", "commence"],
46
+ "Feedback": ["feedback", "comments", "review", "opinion", "suggestion", "critique", "rating"],
47
+ "Online Meetings": ["meeting", "meeting code", "passcode", "join meeting", "zoom", "zoom link"],
48
+ "Event Inquiries": ["event", "webinar", "meeting", "conference", "session", "seminar", "workshop", "invitation"],
49
+ "Payment Issues": ["payment", "billing", "transaction", "charge", "fee", "invoice", "refund", "receipt"],
50
+ "Registration Issues": ["registration", "register", "sign up", "enroll", "join", "signup", "enrollment"],
51
+ "Service Requests": ["service", "support", "request", "assistance", "help", "aid", "maintenance"],
52
+ "Account Issues": ["account", "profile", "update", "activation", "deactivation", "credentials", "reset"],
53
+ "Product Information": ["product", "service", "details", "info", "information", "specifications", "features"],
54
+ "Order Status": ["order", "status", "tracking", "shipment", "delivery", "purchase", "dispatch"],
55
+ "Miscellaneous": []
56
+ }
57
+
58
+ def categorize_question(question):
59
+ # Split the question into words
60
+ words = question.split()
61
+
62
+ # Check if the question has only one word
63
+ if len(words) == 1:
64
+ single_word = words[0].lower()
65
+ # Check if the single word is in the Start of Conversation category
66
+ if any(single_word in keyword for keyword in categories_keywords["Start of Conversation"]):
67
+ return "Start of Conversation"
68
+ else:
69
+ return "End of Conversation"
70
+
71
+ # Categorization of other queries
72
+ for category, keywords in categories_keywords.items():
73
+ if any(keyword.lower() in question.lower() for keyword in keywords):
74
+ return category
75
+ return "Miscellaneous"
76
+
77
+
78
+
79
+ def preprocess_data(df):
80
+ df.rename(columns={'Question Asked': 'texts'}, inplace=True)
81
+ df['texts'] = df['texts'].astype(str).str.lower()
82
+ df['texts'] = df['texts'].apply(lambda text: re.sub(r'https?://\S+|www\.\S+', '', text))
83
+
84
+ def remove_emoji(string):
85
+ emoji_pattern = re.compile("["
86
+ u"\U0001F600-\U0001F64F"
87
+ u"\U0001F300-\U0001F5FF"
88
+ u"\U0001F680-\U0001F6FF"
89
+ u"\U0001F1E0-\U0001F1FF"
90
+ u"\U00002702-\U000027B0"
91
+ u"\U000024C2-\U0001F251"
92
+ "]+", flags=re.UNICODE)
93
+ return emoji_pattern.sub(r'', string)
94
+
95
+ df['texts'] = df['texts'].apply(remove_emoji)
96
+
97
+ custom_synonyms = {
98
+ 'application': ['form'],
99
+ 'apply': ['fill', 'applied'],
100
+ 'work': ['job'],
101
+ 'salary': ['stipend', 'pay', 'payment', 'paid'],
102
+ 'test': ['online test', 'amcat test', 'exam', 'assessment'],
103
+ 'pass': ['clear', 'selected', 'pass or not'],
104
+ 'result': ['outcome', 'mark', 'marks'],
105
+ 'thanks': ["thanks a lot to you", "thankyou so much", "thank you so much", "tysm", "thank you",
106
+ "okaythank", "thx", "ty", "thankyou", "thank", "thank u"],
107
+ 'interview': ["pi"]
108
+ }
109
+
110
+ for original_word, synonym_list in custom_synonyms.items():
111
+ for synonym in synonym_list:
112
+ pattern = r"\b" + synonym + r"\b"
113
+ df['texts'] = df['texts'].str.replace(pattern, original_word, regex=True)
114
+
115
+ spam_list = ["click here", "free", "recharge", "limited", "discount", "money back guarantee", "aaj", "kal", "mein",
116
+ "how can i help you", "how can we help you", "how we can help you", "follow", "king", "contacting", "gar",
117
+ "kirke", "subscribe", "youtube", "jio", "insta", "make money", "b2b", "sent using truecaller"]
118
+
119
+ for spam_phrase in spam_list:
120
+ pattern = r"\b" + re.escape(spam_phrase) + r"\b"
121
+ df = df[~df['texts'].str.contains(pattern)]
122
+
123
+ def remove_punctuations(text):
124
+ return re.sub(r'[^\w\s]', '', text)
125
+
126
+ df['texts'] = df['texts'].apply(remove_punctuations)
127
+ df['texts'] = df['texts'].str.strip()
128
+ df = df[df['texts'] != '']
129
+
130
+ # Categorize the texts
131
+ df['Category'] = df['texts'].apply(categorize_question)
132
+
133
+ return df
134
+
135
+ def cluster_data(df, num_clusters):
136
+ vectorizer = TfidfVectorizer(stop_words='english')
137
+ X = vectorizer.fit_transform(df['texts'])
138
+
139
+ kmeans = KMeans(n_clusters=num_clusters, random_state=0)
140
+ kmeans.fit(X)
141
+ df['Cluster'] = kmeans.labels_
142
+
143
+ return df, kmeans
144
+
145
+ def generate_wordcloud(df):
146
+ text = " ".join(df['texts'].tolist())
147
+ stopwords = set(STOPWORDS)
148
+ wordcloud = WordCloud(
149
+ width=800,
150
+ height=400,
151
+ background_color='white',
152
+ max_words=300,
153
+ collocations=False,
154
+ min_font_size=10,
155
+ max_font_size=200,
156
+ stopwords=stopwords,
157
+ prefer_horizontal=1.0,
158
+ scale=2,
159
+ relative_scaling=0.5,
160
+ random_state=42
161
+ ).generate(text)
162
+
163
+ plt.figure(figsize=(15, 7))
164
+ plt.imshow(wordcloud, interpolation='bilinear')
165
+ plt.axis('off')
166
+ buf = BytesIO()
167
+ plt.savefig(buf, format='png')
168
+ buf.seek(0)
169
+ img = Image.open(buf)
170
+ return img
171
+
172
+ def generate_bar_chart(df, num_clusters_to_display):
173
+ # Exclude common words from the top words
174
+ common_words = {'i', 'you', 'thanks', 'thank', 'ok', 'okay', 'sure', 'done'}
175
+
176
+ top_categories = df['Category'].value_counts().index[:num_clusters_to_display]
177
+ df_top_categories = df[df['Category'].isin(top_categories)]
178
+
179
+ category_top_words = df_top_categories.groupby('Category', observed=False)['texts'].apply(lambda x: ' '.join(x)).reset_index()
180
+ category_top_words['top_word'] = category_top_words['texts'].apply(lambda x: ' '.join([word for word in pd.Series(x.split()).value_counts().index if word not in common_words][:3]))
181
+ category_sizes = df_top_categories['Category'].value_counts().reset_index()
182
+ category_sizes.columns = ['Category', 'Count']
183
+ category_sizes = category_sizes.merge(category_top_words[['Category', 'top_word']], on='Category')
184
+
185
+ fig = px.bar(category_sizes, x='Category', y='Count', text='top_word', title='Category Frequency with Top Words')
186
+ fig.update_traces(textposition='outside')
187
+ fig.update_layout(xaxis_title='Category', yaxis_title='Frequency', showlegend=False)
188
+
189
+ buf = BytesIO()
190
+ fig.write_image(buf, format='png')
191
+ buf.seek(0)
192
+ img = Image.open(buf)
193
+ return img
194
+
195
+ def main(file, num_clusters_to_display):
196
+ try:
197
+ df = pd.read_csv(file)
198
+
199
+ # Filter by 'Fallback Message shown'
200
+ df = df[df['Answer'] == 'Fallback Message shown']
201
+
202
+ df = preprocess_data(df)
203
+
204
+ # Get category sizes and sort by size in ascending order
205
+ category_sizes = df['Category'].value_counts().reset_index()
206
+ category_sizes.columns = ['Category', 'Count']
207
+ sorted_categories = category_sizes.sort_values(by='Count', ascending=True)['Category'].tolist()
208
+
209
+ # Get the largest x categories as specified by num_clusters_to_display
210
+ largest_categories = sorted_categories[:num_clusters_to_display]
211
+
212
+ # Filter the dataframe to include only the largest categories
213
+ filtered_df = df[df['Category'].isin(largest_categories)]
214
+
215
+ # Sort the dataframe by Category
216
+ filtered_df = filtered_df.sort_values(by='Category')
217
+
218
+ wordcloud_img = generate_wordcloud(filtered_df)
219
+ bar_chart_img = generate_bar_chart(filtered_df, num_clusters_to_display)
220
+
221
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmpfile:
222
+ filtered_df.to_csv(tmpfile.name, index=False)
223
+ csv_file_path = tmpfile.name
224
+
225
+ return csv_file_path, wordcloud_img, bar_chart_img
226
+ except Exception as e:
227
+ print(f"Error: {e}")
228
+ return str(e), None, None
229
+
230
+ interface = gr.Interface(
231
+ fn=main,
232
+ inputs=[
233
+ gr.File(label="Upload CSV File (.csv)"),
234
+ gr.Slider(label="Number of Categories to Display", minimum=1, maximum=15, step=1, value=5)
235
+ ],
236
+ outputs=[
237
+ gr.File(label="Categorized Data CSV"),
238
+ gr.Image(label="Word Cloud"),
239
+ gr.Image(label="Bar Chart")
240
+ ],
241
+ title="Unanswered User Queries Categorization",
242
+ description="Categorize unanswered user queries into predefined categories"
243
+ )
244
+
245
+ interface.launch(share=True)
246
+
247
+
248
+ In this code, why does the selection of 'number of categories' (slider) affect the quality of the output? I want this slider to ONLY change the number of cateogies visible, not the actual categorization itself. However, when this slider is changed, it does not accurately display only the x largest categories. Additionally, the bar graph and the word cloud should be INDEPENDENT of this slider and should act on the data as a whole regardless of the slider.
249
+ ChatGPT
250
+ Memory updated
251
+ The issue you're experiencing with the slider affecting the output is due to the way the filtering is implemented before generating the visualizations. To ensure that the slider only affects the number of categories displayed and not the actual categorization or the visualizations, we need to modify the code accordingly.
252
+
253
+ Here’s the updated code:
254
+
255
+ python
256
+ Copy code
257
+ import gradio as gr
258
+ import pandas as pd
259
+ from sklearn.feature_extraction.text import TfidfVectorizer
260
+ from sklearn.cluster import KMeans
261
+ import re
262
+ from io import BytesIO
263
+ import tempfile
264
+ from wordcloud import WordCloud, STOPWORDS
265
+ import matplotlib.pyplot as plt
266
+ import plotly.express as px
267
+ from PIL import Image
268
+
269
+ categories_keywords = {
270
+ "Application Status": ["application status", "application", "status", "submitted", "processing", "pending", "approval", "rejected", "accepted"],
271
+ "Volunteering": ["volunteer", "volunteering", "help out", "assist", "volunteer work", "volunteer opportunities"],
272
+ "Certificates": ["certificate", "certificates", "completion", "certification", "accreditation", "proof", "document", "certified"],
273
+ "Job Opportunities": ["job", "opportunity", "career", "vacancy", "position", "employment", "hiring", "recruitment", "internship"],
274
+ "Surveys and Forms": ["survey", "form", "forms", "questionnaire", "feedback form", "response", "fill out", "submission"],
275
+ "General Queries": ["hello", "hi", "help", "general", "query", "question", "info", "information", "inquiry", "ask"],
276
+ "Spam": ["spam", "subscribe", "remove", "stop", "junk", "block", "opt-out", "watch my video", "click on this link", "win prize"],
277
+ "Rescheduling and Postponing": ["reschedule", "postpone", "delay", "change date", "new time", "rearrange", "shift", "adjust timing"],
278
+ "Contact and Communication Issues": ["contact", "communicate", "communication", "reach out", "phone", "email", "address", "details"],
279
+ "Email and Credentials Issues": ["email", "credentials", "login", "password", "access", "username", "account", "verification", "reset"],
280
+ "Timing and Scheduling": ["timing", "schedule", "scheduling", "time", "appointment", "availability", "calendar", "book", "slot"],
281
+ "Salary and Benefits": ["salary", "benefits", "pay", "compensation", "wages", "earnings", "package", "remuneration", "incentives"],
282
+ "Technical Issues": ["technical", "issue", "problem", "error", "bug", "glitch", "fix", "troubleshoot", "support"],
283
+ "End of Conversation": ["bye", "thank you", "thanks", "goodbye", "see you", "later", "end", "close", "sign off"],
284
+ "Start of Conversation": ["start", "begin", "hello", "hi", "initiate", "greet", "greeting", "open", "commence"],
285
+ "Feedback": ["feedback", "comments", "review", "opinion", "suggestion", "critique", "rating"],
286
+ "Online Meetings": ["meeting", "meeting code", "passcode", "join meeting", "zoom", "zoom link"],
287
+ "Event Inquiries": ["event", "webinar", "meeting", "conference", "session", "seminar", "workshop", "invitation"],
288
+ "Payment Issues": ["payment", "billing", "transaction", "charge", "fee", "invoice", "refund", "receipt"],
289
+ "Registration Issues": ["registration", "register", "sign up", "enroll", "join", "signup", "enrollment"],
290
+ "Service Requests": ["service", "support", "request", "assistance", "help", "aid", "maintenance"],
291
+ "Account Issues": ["account", "profile", "update", "activation", "deactivation", "credentials", "reset"],
292
+ "Product Information": ["product", "service", "details", "info", "information", "specifications", "features"],
293
+ "Order Status": ["order", "status", "tracking", "shipment", "delivery", "purchase", "dispatch"],
294
+ "Miscellaneous": []
295
+ }
296
+
297
+ def categorize_question(question):
298
+ words = question.split()
299
+ if len(words) == 1:
300
+ single_word = words[0].lower()
301
+ if any(single_word in keyword for keyword in categories_keywords["Start of Conversation"]):
302
+ return "Start of Conversation"
303
+ else:
304
+ return "End of Conversation"
305
+
306
+ for category, keywords in categories_keywords.items():
307
+ if any(keyword.lower() in question.lower() for keyword in keywords):
308
+ return category
309
+ return "Miscellaneous"
310
+
311
+ def preprocess_data(df):
312
+ df.rename(columns={'Question Asked': 'texts'}, inplace=True)
313
+ df['texts'] = df['texts'].astype(str).str.lower()
314
+ df['texts'] = df['texts'].apply(lambda text: re.sub(r'https?://\S+|www\.\S+', '', text))
315
+
316
+ def remove_emoji(string):
317
+ emoji_pattern = re.compile("["
318
+ u"\U0001F600-\U0001F64F"
319
+ u"\U0001F300-\U0001F5FF"
320
+ u"\U0001F680-\U0001F6FF"
321
+ u"\U0001F1E0-\U0001F1FF"
322
+ u"\U00002702-\U000027B0"
323
+ u"\U000024C2-\U0001F251"
324
+ "]+", flags=re.UNICODE)
325
+ return emoji_pattern.sub(r'', string)
326
+
327
+ df['texts'] = df['texts'].apply(remove_emoji)
328
+
329
+ custom_synonyms = {
330
+ 'application': ['form'],
331
+ 'apply': ['fill', 'applied'],
332
+ 'work': ['job'],
333
+ 'salary': ['stipend', 'pay', 'payment', 'paid'],
334
+ 'test': ['online test', 'amcat test', 'exam', 'assessment'],
335
+ 'pass': ['clear', 'selected', 'pass or not'],
336
+ 'result': ['outcome', 'mark', 'marks'],
337
+ 'thanks': ["thanks a lot to you", "thankyou so much", "thank you so much", "tysm", "thank you",
338
+ "okaythank", "thx", "ty", "thankyou", "thank", "thank u"],
339
+ 'interview': ["pi"]
340
+ }
341
+
342
+ for original_word, synonym_list in custom_synonyms.items():
343
+ for synonym in synonym_list:
344
+ pattern = r"\b" + synonym + r"\b"
345
+ df['texts'] = df['texts'].str.replace(pattern, original_word, regex=True)
346
+
347
+ spam_list = ["click here", "free", "recharge", "limited", "discount", "money back guarantee", "aaj", "kal", "mein",
348
+ "how can i help you", "how can we help you", "how we can help you", "follow", "king", "contacting", "gar",
349
+ "kirke", "subscribe", "youtube", "jio", "insta", "make money", "b2b", "sent using truecaller"]
350
+
351
+ for spam_phrase in spam_list:
352
+ pattern = r"\b" + re.escape(spam_phrase) + r"\b"
353
+ df = df[~df['texts'].str.contains(pattern)]
354
+
355
+ def remove_punctuations(text):
356
+ return re.sub(r'[^\w\s]', '', text)
357
+
358
+ df['texts'] = df['texts'].apply(remove_punctuations)
359
+ df['texts'] = df['texts'].str.strip()
360
+ df = df[df['texts'] != '']
361
+
362
+ df['Category'] = df['texts'].apply(categorize_question)
363
+
364
+ return df
365
+
366
+ def cluster_data(df, num_clusters):
367
+ vectorizer = TfidfVectorizer(stop_words='english')
368
+ X = vectorizer.fit_transform(df['texts'])
369
+
370
+ kmeans = KMeans(n_clusters=num_clusters, random_state=0)
371
+ kmeans.fit(X)
372
+ df['Cluster'] = kmeans.labels_
373
+
374
+ return df, kmeans
375
+
376
+ def generate_wordcloud(df):
377
+ text = " ".join(df['texts'].tolist())
378
+ stopwords = set(STOPWORDS)
379
+ wordcloud = WordCloud(
380
+ width=800,
381
+ height=400,
382
+ background_color='white',
383
+ max_words=300,
384
+ collocations=False,
385
+ min_font_size=10,
386
+ max_font_size=200,
387
+ stopwords=stopwords,
388
+ prefer_horizontal=1.0,
389
+ scale=2,
390
+ relative_scaling=0.5,
391
+ random_state=42
392
+ ).generate(text)
393
+
394
+ plt.figure(figsize=(15, 7))
395
+ plt.imshow(wordcloud, interpolation='bilinear')
396
+ plt.axis('off')
397
+ buf = BytesIO()
398
+ plt.savefig(buf, format='png')
399
+ buf.seek(0)
400
+ img = Image.open(buf)
401
+ return img
402
+
403
+ def generate_bar_chart(df, num_clusters_to_display):
404
+ common_words = {'i', 'you', 'thanks', 'thank', 'ok', 'okay', 'sure', 'done'}
405
+
406
+ top_categories = df['Category'].value_counts().index[:num_clusters_to_display]
407
+ df_top_categories = df[df['Category'].isin(top_categories)]
408
+
409
+ category_top_words = df_top_categories.groupby('Category', observed=False)['texts'].apply(lambda x: ' '.join(x)).reset_index()
410
+ category_top_words['top_word'] = category_top_words['texts'].apply(lambda x: ' '.join([word for word in pd.Series(x.split()).value_counts().index if word not in common_words][:3]))
411
+ category_sizes = df_top_categories['Category'].value_counts().reset_index()
412
+ category_sizes.columns = ['Category', 'Count']
413
+ category_sizes = category_sizes.merge(category_top_words[['Category', 'top_word']], on='Category')
414
+
415
+ fig = px.bar(category_sizes, x='Category', y='Count', text='top_word', title='Category Frequency with Top Words')
416
+ fig.update_traces(textposition='outside')
417
+ fig.update_layout(xaxis_title='Category', yaxis_title='Frequency', showlegend=False)
418
+
419
+ buf = BytesIO()
420
+ fig.write_image(buf, format='png')
421
+ buf.seek(0)
422
+ img = Image.open(buf)
423
+ return img
424
+
425
+ def main(file, num_clusters_to_display):
426
+ try:
427
+ df = pd.read_csv(file)
428
+
429
+ df = df[df['Answer'] == 'Fallback Message shown']
430
+
431
+ df = preprocess_data(df)
432
+
433
+ wordcloud_img = generate_wordcloud(df)
434
+ bar_chart_img = generate_bar_chart(df, num_clusters_to_display)
435
+
436
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmpfile:
437
+ df.to_csv(tmpfile.name, index=False)
438
+ csv_file_path = tmpfile.name
439
+
440
+ return csv_file_path, wordcloud_img, bar_chart_img
441
+ except Exception as e:
442
+ print(f"Error: {e}")
443
+ return str(e), None, None
444
+
445
+ interface = gr.Interface(
446
+ fn=main,
447
+ inputs=[
448
+ gr.File(label="Upload CSV File (.csv)"),
449
+ gr.Slider(label="Number of Categories to Display", minimum=1, maximum=15, step=1, value=5)
450
+ ],
451
+ outputs=[
452
+ gr.File(label="Categorized Data CSV"),
453
+ gr.Image(label="Word Cloud"),
454
+ gr.Image(label="Bar Chart")
455
+ ],
456
+ title="Unanswered User Queries Categorization",
457
+ description="Categorize unanswered user queries into predefined categories"
458
+ )
459
+
460
+ interface.launch(share=True)
461
+ Changes made:
462
+
463
+ Categorization: The preprocess_data function now categorizes the data without any filtering based on the slider value.
464
+ Visualizations: The word cloud and bar chart functions use the entire categorized data to generate the visuals.
465
+ Filtering: The filtering based on the slider value is only applied within the generate_bar_chart function to limit the number of categories displayed in the bar chart.
466
+ With these changes, the slider will only affect the number of categories displayed in the bar chart, and the word cloud will be generated using the entire dataset regardless of the slider value. The CSV output will also include all categorized data.
467
+
468
+ Now the barchart works as intended, but the word cloud doesn't. Can we restore the old word cloud mechanism while still maintaining the new bar chart funcitonality, so both work as intended?
469
+ ChatGPT
470
+ Sure, we can restore the old word cloud mechanism to ensure it functions as intended while keeping the new bar chart functionality. Here is the updated code:
471
+
472
+ python
473
+ Copy code
474
+ import gradio as gr
475
+ import pandas as pd
476
+ from sklearn.feature_extraction.text import TfidfVectorizer
477
+ from sklearn.cluster import KMeans
478
+ import re
479
+ from io import BytesIO
480
+ import tempfile
481
+ from wordcloud import WordCloud, STOPWORDS
482
+ import matplotlib.pyplot as plt
483
+ import plotly.express as px
484
+ from PIL import Image
485
+
486
  categories_keywords = {
487
+ "Application Status": ["application status", "application", "status", "submitted", "processing", "pending", "approval", "rejected", "accepted"],
488
+ "Volunteering": ["volunteer", "volunteering", "help out", "assist", "volunteer work", "volunteer opportunities"],
489
+ "Certificates": ["certificate", "certificates", "completion", "certification", "accreditation", "proof", "document", "certified"],
490
+ "Job Opportunities": ["job", "opportunity", "career", "vacancy", "position", "employment", "hiring", "recruitment", "internship"],
491
+ "Surveys and Forms": ["survey", "form", "forms", "questionnaire", "feedback form", "response", "fill out", "submission"],
492
+ "General Queries": ["hello", "hi", "help", "general", "query", "question", "info", "information", "inquiry", "ask"],
493
+ "Spam": ["spam", "subscribe", "remove", "stop", "junk", "block", "opt-out", "watch my video", "click on this link", "win prize"],
494
+ "Rescheduling and Postponing": ["reschedule", "postpone", "delay", "change date", "new time", "rearrange", "shift", "adjust timing"],
495
+ "Contact and Communication Issues": ["contact", "communicate", "communication", "reach out", "phone", "email", "address", "details"],
496
+ "Email and Credentials Issues": ["email", "credentials", "login", "password", "access", "username", "account", "verification", "reset"],
497
+ "Timing and Scheduling": ["timing", "schedule", "scheduling", "time", "appointment", "availability", "calendar", "book", "slot"],
498
+ "Salary and Benefits": ["salary", "benefits", "pay", "compensation", "wages", "earnings", "package", "remuneration", "incentives"],
499
+ "Technical Issues": ["technical", "issue", "problem", "error", "bug", "glitch", "fix", "troubleshoot", "support"],
500
+ "End of Conversation": ["bye", "thank you", "thanks", "goodbye", "see you", "later", "end", "close", "sign off"],
501
+ "Start of Conversation": ["start", "begin", "hello", "hi", "initiate", "greet", "greeting", "open", "commence"],
502
+ "Feedback": ["feedback", "comments", "review", "opinion", "suggestion", "critique", "rating"],
503
+ "Online Meetings": ["meeting", "meeting code", "passcode", "join meeting", "zoom", "zoom link"],
504
+ "Event Inquiries": ["event", "webinar", "meeting", "conference", "session", "seminar", "workshop", "invitation"],
505
+ "Payment Issues": ["payment", "billing", "transaction", "charge", "fee", "invoice", "refund", "receipt"],
506
+ "Registration Issues": ["registration", "register", "sign up", "enroll", "join", "signup", "enrollment"],
507
+ "Service Requests": ["service", "support", "request", "assistance", "help", "aid", "maintenance"],
508
+ "Account Issues": ["account", "profile", "update", "activation", "deactivation", "credentials", "reset"],
509
+ "Product Information": ["product", "service", "details", "info", "information", "specifications", "features"],
510
+ "Order Status": ["order", "status", "tracking", "shipment", "delivery", "purchase", "dispatch"],
511
+ "Miscellaneous": []
512
  }
513
 
514