mgbam commited on
Commit
99776c8
·
verified ·
1 Parent(s): d426068

Update modules/text.py

Browse files
Files changed (1) hide show
  1. modules/text.py +77 -0
modules/text.py CHANGED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modules/text.py
2
+
3
+ # -*- coding: utf-8 -*-
4
+ #
5
+ # PROJECT: CognitiveEDA v5.0 - The QuantumLeap Intelligence Platform
6
+ #
7
+ # DESCRIPTION: Specialized module for basic text analysis, focused on generating
8
+ # a word cloud visualization from a text-heavy column.
9
+
10
+ import base64
11
+ import io
12
+ import logging
13
+
14
+ import pandas as pd
15
+ from wordcloud import WordCloud
16
+
17
+ def generate_word_cloud(df: pd.DataFrame, text_col: str) -> str:
18
+ """
19
+ Generates a word cloud from a text column and returns it as an HTML object.
20
+
21
+ The function processes the text, generates a word cloud image, encodes it
22
+ in Base64, and embeds it within an HTML string for display in Gradio.
23
+
24
+ Args:
25
+ df: The input DataFrame.
26
+ text_col: The name of the column containing text data.
27
+
28
+ Returns:
29
+ An HTML string containing the word cloud image or a status/error message.
30
+ """
31
+ # 1. Input Validation
32
+ if not text_col:
33
+ return "<p style='text-align:center; padding: 20px;'>Select a text column to generate a word cloud.</p>"
34
+
35
+ if text_col not in df.columns:
36
+ return f"<p style='text-align:center; color:red; padding: 20px;'>Error: Column '{text_col}' not found in the dataset.</p>"
37
+
38
+ try:
39
+ logging.info(f"Generating word cloud for column '{text_col}'")
40
+
41
+ # 2. Text Corpus Preparation
42
+ # Concatenate all non-null text entries into a single string
43
+ text_corpus = ' '.join(df[text_col].dropna().astype(str))
44
+
45
+ if not text_corpus.strip():
46
+ logging.warning(f"Column '{text_col}' contains no text data to generate a cloud.")
47
+ return "<p style='text-align:center; padding: 20px;'>No text data available in this column to generate a cloud.</p>"
48
+
49
+ # 3. Word Cloud Generation
50
+ wordcloud = WordCloud(
51
+ width=800,
52
+ height=400,
53
+ background_color='white',
54
+ colormap='viridis',
55
+ max_words=150,
56
+ collocations=False # Avoids generating two-word phrases
57
+ ).generate(text_corpus)
58
+
59
+ # 4. Image Encoding
60
+ buf = io.BytesIO()
61
+ wordcloud.to_image().save(buf, format='png')
62
+ img_str = base64.b64encode(buf.getvalue()).decode('utf-8')
63
+
64
+ # 5. HTML Output
65
+ # The style attribute makes the image responsive to container width
66
+ html_content = (
67
+ f'<div style="text-align:center; padding: 10px;">'
68
+ f'<img src="data:image/png;base64,{img_str}" alt="Word Cloud for {text_col}" '
69
+ f'style="border-radius: 8px; max-width: 100%; height: auto;">'
70
+ f'</div>'
71
+ )
72
+ return html_content
73
+
74
+ except Exception as e:
75
+ logging.error(f"Word cloud generation failed for column '{text_col}': {e}", exc_info=True)
76
+ error_msg = f"Could not generate word cloud. An unexpected error occurred: {e}"
77
+ return f"<p style='text-align:center; color:red; padding: 20px;'>❌ **Error:** {error_msg}</p>"