aghilTQ commited on
Commit
6fea244
Β·
verified Β·
1 Parent(s): a04d78d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +50 -74
src/streamlit_app.py CHANGED
@@ -18,20 +18,23 @@ def get_pyphen_dict():
18
  return pyphen.Pyphen(lang='en')
19
 
20
  def generate_color_palette(num_colors: int) -> List[str]:
21
- """Generate distinct colors for syllables"""
22
- colors = [
23
- "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7",
24
- "#DDA0DD", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E9",
25
- "#F8C471", "#82E0AA", "#F1948A", "#85C1E9", "#D7BDE2",
26
- "#A9DFBF", "#F9E79F", "#D5A6BD", "#AED6F1", "#ABEBC6"
 
27
  ]
28
 
29
- # If we need more colors than predefined, generate random ones
30
- while len(colors) < num_colors:
31
- color = f"#{random.randint(100, 255):02x}{random.randint(100, 255):02x}{random.randint(100, 255):02x}"
32
- colors.append(color)
 
 
33
 
34
- return colors[:num_colors]
35
 
36
  def syllabify_word(word: str, pyphen_dict) -> List[str]:
37
  """Syllabify a single word using pyphen"""
@@ -64,43 +67,25 @@ def syllabify_word(word: str, pyphen_dict) -> List[str]:
64
  except:
65
  return [clean_word]
66
 
67
- def process_text(text: str) -> Tuple[List[Tuple[str, str]], List[Tuple[str, List[Tuple[str, str]]]]]:
68
- """Process text and return colored words and syllable breakdown"""
69
  pyphen_dict = get_pyphen_dict()
70
 
71
- # Split into words while preserving spaces
72
- words = re.findall(r'\b\w+\b', text) # Only actual words, no spaces
73
-
74
- colored_words = []
75
  syllable_breakdown = []
76
 
77
- # Process original text with spaces preserved
78
- text_parts = re.findall(r'\S+|\s+', text)
79
-
80
- word_index = 0
81
- for part in text_parts:
82
- if part.strip() and re.match(r'\w', part): # If it's a word
83
- if word_index < len(words):
84
- word = words[word_index]
85
- syllables_list = syllabify_word(word, pyphen_dict)
86
-
87
- # Generate colors for this word's syllables
88
- colors = generate_color_palette(len(syllables_list))
89
-
90
- # For original text, color with first syllable color
91
- colored_words.append((part, colors[0] if colors else "#000000"))
92
-
93
- # Add to syllable breakdown (no duplicates)
94
- syllable_colored = [(syl, colors[i % len(colors)]) for i, syl in enumerate(syllables_list)]
95
- syllable_breakdown.append((word, syllable_colored))
96
-
97
- word_index += 1
98
- else:
99
- colored_words.append((part, "#000000"))
100
- else:
101
- colored_words.append((part, "#000000")) # Spaces and punctuation
102
 
103
- return colored_words, syllable_breakdown
104
 
105
  def display_colored_text(colored_words: List[Tuple[str, str]]):
106
  """Display text with colored words"""
@@ -150,23 +135,19 @@ def main():
150
  help="Enter any text to see how words are broken down into syllables"
151
  )
152
 
153
- if input_text.strip():
 
 
 
154
  # Process the text
155
- colored_words, syllable_breakdown = process_text(input_text)
156
-
157
- # Create two columns
158
- col1, col2 = st.columns(2)
159
 
160
- with col1:
161
- st.subheader("Original Text (Colored by First Syllable)")
162
- display_colored_text(colored_words)
163
-
164
- with col2:
165
- st.subheader("Syllable Breakdown")
166
- display_syllable_breakdown(syllable_breakdown)
167
 
168
  # Statistics
169
- total_words = len([word for word, _ in syllable_breakdown])
170
  total_syllables = sum(len(syls) for _, syls in syllable_breakdown)
171
 
172
  st.markdown(f"**πŸ“Š {total_words} words β€’ {total_syllables} syllables**")
@@ -177,8 +158,11 @@ def main():
177
  counts_text = " β€’ ".join([f"{word}: {len(syllables)}" for word, syllables in syllable_breakdown])
178
  st.markdown(f"<small>{counts_text}</small>", unsafe_allow_html=True)
179
 
180
- else:
181
- st.info("πŸ‘† Enter some text above to see the syllabification in action!")
 
 
 
182
 
183
  # Example
184
  st.subheader("Example")
@@ -187,34 +171,26 @@ def main():
187
 
188
  if st.button("Try Example"):
189
  # Process example
190
- colored_words, syllable_breakdown = process_text(example_text)
191
 
192
- col1, col2 = st.columns(2)
193
-
194
- with col1:
195
- st.subheader("Original Text (Colored)")
196
- display_colored_text(colored_words)
197
-
198
- with col2:
199
- st.subheader("Syllable Breakdown")
200
- display_syllable_breakdown(syllable_breakdown)
201
 
202
  # Show example statistics
203
- total_words = len([word for word, _ in syllable_breakdown])
204
  total_syllables = sum(len(syls) for _, syls in syllable_breakdown)
205
- st.markdown(f"**Example Statistics:** {total_words} words, {total_syllables} syllables")
206
 
207
  # About section
208
  with st.expander("About this tool"):
209
  st.markdown("""
210
  This tool uses the **pyphen** library, which implements the Hunspell hyphenation algorithm.
211
- It provides much more accurate syllabification than simple rule-based approaches.
212
 
213
  **Features:**
214
  - Accurate English syllabification using pyphen
215
- - Color-coded visualization
216
- - Preserves original text formatting
217
- - Shows syllable counts and statistics
218
  - Handles capitalization properly
219
  """)
220
 
 
18
  return pyphen.Pyphen(lang='en')
19
 
20
  def generate_color_palette(num_colors: int) -> List[str]:
21
+ """Generate gray shades for syllables"""
22
+ # Use different shades of gray instead of bright colors
23
+ base_grays = [
24
+ "#2C3E50", "#34495E", "#5D6D7E", "#85929E", "#566573",
25
+ "#515A5A", "#626567", "#797D7F", "#922B21", "#A93226",
26
+ "#B7472A", "#C0392B", "#CD6155", "#D98880", "#E8DAEF",
27
+ "#D7BDE2", "#BB8FCE", "#A569BD", "#8E44AD", "#7D3C98"
28
  ]
29
 
30
+ # Generate more gray shades if needed
31
+ while len(base_grays) < num_colors:
32
+ # Generate random gray shades
33
+ gray_val = random.randint(60, 140)
34
+ color = f"#{gray_val:02x}{gray_val:02x}{gray_val:02x}"
35
+ base_grays.append(color)
36
 
37
+ return base_grays[:num_colors]
38
 
39
  def syllabify_word(word: str, pyphen_dict) -> List[str]:
40
  """Syllabify a single word using pyphen"""
 
67
  except:
68
  return [clean_word]
69
 
70
+ def process_text(text: str) -> List[Tuple[str, List[Tuple[str, str]]]]:
71
+ """Process text and return syllable breakdown only"""
72
  pyphen_dict = get_pyphen_dict()
73
 
74
+ # Split into words
75
+ words = re.findall(r'\b\w+\b', text)
 
 
76
  syllable_breakdown = []
77
 
78
+ for word in words:
79
+ syllables_list = syllabify_word(word, pyphen_dict)
80
+
81
+ # Generate gray colors for this word's syllables
82
+ colors = generate_color_palette(len(syllables_list))
83
+
84
+ # Add to syllable breakdown
85
+ syllable_colored = [(syl, colors[i % len(colors)]) for i, syl in enumerate(syllables_list)]
86
+ syllable_breakdown.append((word, syllable_colored))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ return syllable_breakdown
89
 
90
  def display_colored_text(colored_words: List[Tuple[str, str]]):
91
  """Display text with colored words"""
 
135
  help="Enter any text to see how words are broken down into syllables"
136
  )
137
 
138
+ # Submit button
139
+ submit_clicked = st.button("πŸ” Submit", type="primary", use_container_width=True)
140
+
141
+ if submit_clicked and input_text.strip():
142
  # Process the text
143
+ syllable_breakdown = process_text(input_text)
 
 
 
144
 
145
+ # Display syllable breakdown
146
+ st.subheader("Syllable Breakdown")
147
+ display_syllable_breakdown(syllable_breakdown)
 
 
 
 
148
 
149
  # Statistics
150
+ total_words = len(syllable_breakdown)
151
  total_syllables = sum(len(syls) for _, syls in syllable_breakdown)
152
 
153
  st.markdown(f"**πŸ“Š {total_words} words β€’ {total_syllables} syllables**")
 
158
  counts_text = " β€’ ".join([f"{word}: {len(syllables)}" for word, syllables in syllable_breakdown])
159
  st.markdown(f"<small>{counts_text}</small>", unsafe_allow_html=True)
160
 
161
+ elif submit_clicked and not input_text.strip():
162
+ st.warning("⚠️ Please enter some text first!")
163
+
164
+ elif not submit_clicked:
165
+ st.info("πŸ‘† Enter some text above and click Submit to see the syllabification!")
166
 
167
  # Example
168
  st.subheader("Example")
 
171
 
172
  if st.button("Try Example"):
173
  # Process example
174
+ syllable_breakdown = process_text(example_text)
175
 
176
+ st.subheader("Syllable Breakdown")
177
+ display_syllable_breakdown(syllable_breakdown)
 
 
 
 
 
 
 
178
 
179
  # Show example statistics
180
+ total_words = len(syllable_breakdown)
181
  total_syllables = sum(len(syls) for _, syls in syllable_breakdown)
182
+ st.markdown(f"**πŸ“Š {total_words} words β€’ {total_syllables} syllables**")
183
 
184
  # About section
185
  with st.expander("About this tool"):
186
  st.markdown("""
187
  This tool uses the **pyphen** library, which implements the Hunspell hyphenation algorithm.
188
+ It provides accurate syllabification for English text.
189
 
190
  **Features:**
191
  - Accurate English syllabification using pyphen
192
+ - Gray-scale color coding for easy reading
193
+ - Syllable counts and statistics
 
194
  - Handles capitalization properly
195
  """)
196