truewordcloud 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ Metadata-Version: 2.4
2
+ Name: truewordcloud
3
+ Version: 1.0.0
4
+ Summary: Value-proportional word cloud generator with true size relationships
5
+ Home-page: https://github.com/laurenceanthony/truewordcloud
6
+ Author: Laurence Anthony
7
+ Author-email: Laurence Anthony <anthony@antlabsolutions.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/laurenceanthony/truewordcloud
10
+ Project-URL: Bug Reports, https://github.com/laurenceanthony/truewordcloud/issues
11
+ Project-URL: Source, https://github.com/laurenceanthony/truewordcloud
12
+ Keywords: wordcloud,visualization,text-analysis,frequency,linguistics,data-visualization
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Scientific/Engineering :: Visualization
17
+ Classifier: Topic :: Text Processing :: Linguistic
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.7
21
+ Classifier: Programming Language :: Python :: 3.8
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Requires-Python: >=3.7
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: Pillow>=8.0.0
30
+ Requires-Dist: numpy>=1.19.0
31
+ Requires-Dist: matplotlib>=3.3.0
32
+ Dynamic: author
33
+ Dynamic: home-page
34
+ Dynamic: license-file
35
+ Dynamic: requires-python
36
+
37
+ # TrueWordCloud
38
+
39
+ **Value-Proportional Word Cloud Generator**
40
+
41
+ A word cloud generator that maintains TRUE proportional relationships between values. Unlike traditional word clouds that arbitrarily resize words to fit a canvas, TrueWordCloud ensures font sizes are ALWAYS proportional to the input values.
42
+
43
+ ## Key Features
44
+
45
+ - ✅ **True Proportionality** - Font sizes strictly proportional to input values (no squeezing/normalization)
46
+ - 🎨 **Two Layout Algorithms** - Choose between 'greedy' (fast, deterministic) and 'square' (compact, randomized)
47
+ - 📐 **Dynamic Canvas** - Canvas size determined by content, not pre-fixed dimensions
48
+ - 🔢 **Any Numeric Values** - Works with frequencies, keyness scores, TF-IDF, probabilities, etc.
49
+ - 🎯 **No Overlaps** - Guaranteed non-overlapping word placement
50
+ - 🌈 **Custom Colors** - Flexible color function support
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install truewordcloud
56
+ ```
57
+
58
+ Or install from source:
59
+
60
+ ```bash
61
+ git clone https://github.com/laurenceanthony/truewordcloud.git
62
+ cd truewordcloud
63
+ pip install -e .
64
+ ```
65
+
66
+ ## Quick Start
67
+
68
+ ```python
69
+ from truewordcloud import TrueWordCloud
70
+
71
+ # Simple usage
72
+ values = {'python': 100, 'data': 80, 'science': 75, 'visualization': 60}
73
+ twc = TrueWordCloud(values=values)
74
+ image = twc.generate()
75
+ image.save('wordcloud.png')
76
+ ```
77
+
78
+ ## Layout Algorithms
79
+
80
+ ### Greedy Spiral (method='greedy')
81
+
82
+ **Best for: Speed, reproducibility, circular aesthetics**
83
+
84
+ - ⚡ Fast spiral placement from center outward
85
+ - 🔒 Deterministic (same input → same output)
86
+ - 🎯 Creates radial/circular patterns
87
+ - ✅ Ideal for scientific papers, reports, consistent branding
88
+
89
+ ```python
90
+ twc = TrueWordCloud(values=values, method='greedy')
91
+ ```
92
+
93
+ ### Square Packing (method='square')
94
+
95
+ **Best for: Compact layouts, gap filling, visual variety**
96
+
97
+ - 📦 Center-outward square packing with intelligent gap filling
98
+ - 🎲 Randomized (varied layouts each run)
99
+ - 📐 Maintains roughly square aspect ratio (width ≈ height)
100
+ - ✅ Ideal for presentations, posters, artistic displays
101
+
102
+ ```python
103
+ twc = TrueWordCloud(values=values, method='square')
104
+ ```
105
+
106
+ ## Advanced Usage
107
+
108
+ ### Custom Colors
109
+
110
+ ```python
111
+ def color_func(word, freq, norm_freq):
112
+ # norm_freq is between 0 and 1
113
+ if norm_freq > 0.7:
114
+ return (255, 0, 0) # Red for high frequency
115
+ elif norm_freq > 0.4:
116
+ return (0, 0, 255) # Blue for medium
117
+ else:
118
+ return (128, 128, 128) # Gray for low
119
+
120
+ twc = TrueWordCloud(values=values, color_func=color_func)
121
+ ```
122
+
123
+ ### All Parameters
124
+
125
+ ```python
126
+ twc = TrueWordCloud(
127
+ values={'word': 100, 'cloud': 50}, # Required: word -> value mapping
128
+ method='greedy', # 'greedy' or 'square'
129
+ base_font_size=100, # Font size for max value word
130
+ font_path='/path/to/font.ttf', # Custom font (auto-detected if None)
131
+ min_font_size=10, # Minimum font size
132
+ background_color=(255, 255, 255), # RGB tuple
133
+ margin=2, # Pixels between words
134
+ color_func=None # Custom color function
135
+ )
136
+
137
+ # Generate with statistics
138
+ image, stats = twc.generate_with_stats()
139
+ print(stats) # {'num_words': 2, 'size_range': (50, 100), 'canvas_size': (800, 600), 'method': 'greedy'}
140
+ ```
141
+
142
+ ## Comparison with Traditional Word Clouds
143
+
144
+ | Feature | TrueWordCloud | Traditional Word Clouds |
145
+ |---------|---------------|------------------------|
146
+ | Proportionality | ✅ Strict (font_size ∝ value) | ❌ Arbitrary resizing to fit |
147
+ | Canvas Size | Dynamic (fits content) | Fixed (pre-defined) |
148
+ | Reproducibility | ✅ Greedy method | Sometimes |
149
+ | Layout Options | 2 algorithms | Usually 1 |
150
+ | Value Types | Any numeric | Usually just frequencies |
151
+
152
+ ## Why True Proportionality Matters
153
+
154
+ Traditional word clouds often **lie** about the data:
155
+ - A word with value 100 might be rendered at 80pt
156
+ - A word with value 50 might be rendered at 75pt
157
+ - Ratios like 2:1 become 1.07:1
158
+
159
+ **TrueWordCloud guarantees:**
160
+ - Value 100 → 100pt, Value 50 → 50pt
161
+ - Ratios are preserved: 2:1 stays 2:1
162
+ - Visual size accurately represents data magnitude
163
+
164
+ ## Use Cases
165
+
166
+ - **Linguistic Analysis** - Word frequencies, keyness scores, TF-IDF
167
+ - **Survey Results** - Response counts, satisfaction scores
168
+ - **Scientific Papers** - Maintaining accurate proportional relationships
169
+ - **Marketing** - Brand mentions, sentiment scores
170
+ - **Education** - Concept importance, study time allocation
171
+
172
+ ## Requirements
173
+
174
+ - Python 3.7+
175
+ - Pillow (PIL)
176
+ - numpy
177
+ - matplotlib (for font detection)
178
+
179
+ ## License
180
+
181
+ MIT License - see LICENSE file for details
182
+
183
+ ## Contributing
184
+
185
+ Contributions welcome! Please open an issue or submit a pull request.
186
+
187
+ ## Citation
188
+
189
+ If you use TrueWordCloud in academic work, please cite:
190
+
191
+ ```
192
+ @software{truewordcloud2026,
193
+ title={TrueWordCloud: Value-Proportional Word Cloud Generator},
194
+ author={Laurence Anthony},
195
+ year={2026},
196
+ url={https://github.com/laurenceanthony/truewordcloud}
197
+ }
198
+ ```
199
+
200
+ ## Examples
201
+
202
+ ### Frequency Data
203
+ ```python
204
+ word_frequencies = {
205
+ 'the': 1000, 'Python': 500, 'data': 400, 'analysis': 300,
206
+ 'machine': 250, 'learning': 250, 'algorithm': 200
207
+ }
208
+ twc = TrueWordCloud(values=word_frequencies, method='greedy')
209
+ twc.generate().save('frequencies.png')
210
+ ```
211
+
212
+ ### Keyness Scores
213
+ ```python
214
+ keyness_scores = {
215
+ 'significant': 12.5, 'analysis': 8.3, 'corpus': 6.7,
216
+ 'frequency': 5.2, 'text': 4.1
217
+ }
218
+ twc = TrueWordCloud(values=keyness_scores, method='square', base_font_size=50)
219
+ twc.generate().save('keyness.png')
220
+ ```
221
+
222
+ ### With Custom Styling
223
+ ```python
224
+ from PIL import ImageColor
225
+
226
+ def rainbow_color(word, freq, norm_freq):
227
+ # Rainbow gradient based on frequency
228
+ hue = int(norm_freq * 270) # 0 (red) to 270 (blue)
229
+ return ImageColor.getrgb(f'hsl({hue}, 100%, 50%)')
230
+
231
+ twc = TrueWordCloud(
232
+ values=word_frequencies,
233
+ method='square',
234
+ color_func=rainbow_color,
235
+ background_color=(0, 0, 0), # Black background
236
+ margin=5
237
+ )
238
+ twc.generate().save('rainbow.png')
239
+ ```
240
+
241
+ ## FAQ
242
+
243
+ **Q: Why are the layouts different sizes?**
244
+ A: Canvas size is determined by content. More words or higher values = larger canvas. This maintains true proportions.
245
+
246
+ **Q: Can I fix the canvas size?**
247
+ A: Not directly, as that would require resizing words (breaking true proportionality). Instead, adjust `base_font_size` to control overall scale.
248
+
249
+ **Q: Which method should I use?**
250
+ A: Use `greedy` for speed and reproducibility. Use `square` for compact layouts and visual variety.
251
+
252
+ **Q: How do I make words fit in a specific area?**
253
+ A: Reduce `base_font_size` until the generated canvas is the desired size.
254
+
255
+ ---
256
+
257
+ **Made with ❤️ for accurate data visualization**
@@ -0,0 +1,6 @@
1
+ truewordcloud.py,sha256=HzEzswL4VJhNWqnVrU9uwLmqZRu4Kl5HLH0dsnoU-YY,20659
2
+ truewordcloud-1.0.0.dist-info/licenses/LICENSE,sha256=DFJs-Z1zFkLre2FttqbB2JPzD6N-g_vxIlSgtIoRKQ0,1094
3
+ truewordcloud-1.0.0.dist-info/METADATA,sha256=nzvnB_ts0v4nSaJkCW4ltAhuljP-puZL_FR7AWZhigY,8391
4
+ truewordcloud-1.0.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
5
+ truewordcloud-1.0.0.dist-info/top_level.txt,sha256=q1j1LtzsiloB8PRQ8KDRgZ3Xg_93Y2oLbKVtfADvuWU,14
6
+ truewordcloud-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Laurence Anthony
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ truewordcloud
truewordcloud.py ADDED
@@ -0,0 +1,579 @@
1
+ """
2
+ TrueWordCloud - Value-Proportional Word Cloud Generator
3
+ ========================================================
4
+
5
+ A word cloud generator that maintains TRUE proportional relationships between values.
6
+ Unlike traditional word clouds that arbitrarily resize words to fit a canvas, TrueWordCloud
7
+ ensures font sizes are ALWAYS proportional to the input values.
8
+
9
+ Key Features:
10
+ - Font sizes are ALWAYS proportional to input values (no squeezing/normalization)
11
+ - Two layout algorithms: 'greedy' (fast, deterministic) and 'square' (compact, randomized)
12
+ - Dynamic canvas sizing (content determines size, not pre-fixed dimensions)
13
+ - Works with any numeric values: frequencies, keyness scores, TF-IDF, etc.
14
+
15
+ Usage:
16
+ from truewordcloud import TrueWordCloud
17
+
18
+ # Simple usage
19
+ twc = TrueWordCloud(values={'hello': 100, 'world': 50})
20
+ image = twc.generate()
21
+ image.save('wordcloud.png')
22
+
23
+ # With options
24
+ twc = TrueWordCloud(
25
+ values={'hello': 100, 'world': 50},
26
+ method='square', # or 'greedy'
27
+ base_font_size=100,
28
+ font_path='path/to/font.ttf'
29
+ )
30
+ image, stats = twc.generate_with_stats()
31
+ """
32
+
33
+ from PIL import Image, ImageDraw, ImageFont
34
+ import numpy as np
35
+ from typing import Dict, Tuple, List, Optional
36
+ from dataclasses import dataclass
37
+ import math
38
+ import random
39
+
40
+
41
+ @dataclass
42
+ class WordBox:
43
+ """Represents a word with its rendering properties and position"""
44
+
45
+ word: str
46
+ frequency: float
47
+ font_size: int
48
+ width: int
49
+ height: int
50
+ x: float # Center position
51
+ y: float
52
+ color: Tuple[int, int, int] = (0, 0, 0)
53
+
54
+ @property
55
+ def bbox(self) -> Tuple[float, float, float, float]:
56
+ """Return (left, top, right, bottom)"""
57
+ half_w = self.width / 2
58
+ half_h = self.height / 2
59
+ return (self.x - half_w, self.y - half_h, self.x + half_w, self.y + half_h)
60
+
61
+ def overlaps(self, other: "WordBox", margin: int = 2) -> bool:
62
+ """Check if this word overlaps with another word"""
63
+ l1, t1, r1, b1 = self.bbox
64
+ l2, t2, r2, b2 = other.bbox
65
+
66
+ # Add margin for visual separation
67
+ l1 -= margin
68
+ t1 -= margin
69
+ r1 += margin
70
+ b1 += margin
71
+
72
+ return not (r1 < l2 or r2 < l1 or b1 < t2 or b2 < t1)
73
+
74
+
75
+ class TrueWordCloud:
76
+ """
77
+ Value-proportional word cloud generator.
78
+
79
+ This generator maintains TRUE proportional relationships - font sizes are always
80
+ proportional to input values, never arbitrarily resized.
81
+
82
+ Two layout methods available:
83
+
84
+ 'greedy' (default):
85
+ - Fast spiral placement from center outward
86
+ - Deterministic (same input → same output)
87
+ - Creates radial/circular patterns
88
+ - Best for: speed, reproducibility, circular aesthetics
89
+
90
+ 'square':
91
+ - Center-outward square packing with gap filling
92
+ - Randomized (varied layouts each run)
93
+ - Creates compact, roughly square layouts
94
+ - Best for: compact layouts, gap filling, visual variety
95
+
96
+ Args:
97
+ values: Dictionary mapping words to numeric values (frequencies, scores, etc.)
98
+ method: Layout algorithm - 'greedy' or 'square' (default: 'greedy')
99
+ base_font_size: Font size for maximum value word (default: 100)
100
+ font_path: Path to TrueType font file (default: system font)
101
+ min_font_size: Minimum font size for words (default: 10)
102
+ background_color: RGB tuple for background (default: white)
103
+ margin: Pixels between words (default: 2)
104
+ color_func: Function to generate colors, receives (word, freq, norm_freq)
105
+ """
106
+
107
+ def __init__(
108
+ self,
109
+ values: Dict[str, float],
110
+ method: str = "greedy",
111
+ base_font_size: int = 100,
112
+ font_path: Optional[str] = None,
113
+ min_font_size: int = 10,
114
+ background_color: Tuple[int, int, int] = (255, 255, 255),
115
+ margin: int = 2,
116
+ color_func: Optional[callable] = None,
117
+ ):
118
+ self.values = values
119
+ self.method = method.lower()
120
+ if self.method not in ['greedy', 'square']:
121
+ raise ValueError(f"method must be 'greedy' or 'square', got '{method}'")
122
+
123
+ self.base_font_size = base_font_size
124
+ self.font_path = font_path or self._get_default_font()
125
+ self.min_font_size = min_font_size
126
+ self.background_color = background_color
127
+ self.margin = margin
128
+ self.color_func = color_func or self._default_color_func
129
+
130
+ self.words: List[WordBox] = []
131
+
132
+ def _get_default_font(self) -> str:
133
+ """Try to find a suitable default font"""
134
+ import matplotlib.font_manager as fm
135
+ import platform
136
+
137
+ system = platform.system()
138
+
139
+ # Platform-specific fonts (without hyphens to avoid parse errors)
140
+ if system == "Windows":
141
+ candidates = ["Arial", "Segoe UI", "Calibri", "Verdana"]
142
+ elif system == "Darwin": # macOS
143
+ candidates = ["Helvetica", "Arial", "SF Pro Display"]
144
+ else: # Linux
145
+ candidates = ["DejaVu Sans", "Liberation Sans", "FreeSans"]
146
+
147
+ # Try each candidate
148
+ for font_name in candidates:
149
+ try:
150
+ matches = [
151
+ f.fname
152
+ for f in fm.fontManager.ttflist
153
+ if font_name.lower() in f.name.lower()
154
+ ]
155
+ if matches:
156
+ return matches[0]
157
+ except:
158
+ continue
159
+
160
+ # Fallback to any font
161
+ if fm.fontManager.ttflist:
162
+ return fm.fontManager.ttflist[0].fname
163
+
164
+ raise RuntimeError("No TrueType fonts found on system")
165
+
166
+ def _default_color_func(self, word: str, freq: float, norm_freq: float) -> Tuple[int, int, int]:
167
+ """Default color function - black"""
168
+ return (0, 0, 0)
169
+
170
+ def _calculate_font_sizes(self) -> Dict[str, int]:
171
+ """Calculate true proportional font sizes"""
172
+ if not self.values:
173
+ return {}
174
+
175
+ max_value = max(self.values.values())
176
+ if max_value == 0:
177
+ return {word: self.min_font_size for word in self.values}
178
+
179
+ font_sizes = {}
180
+ for word, value in self.values.items():
181
+ # True proportional scaling
182
+ size = int(self.base_font_size * (value / max_value))
183
+ # Enforce minimum
184
+ font_sizes[word] = max(size, self.min_font_size)
185
+
186
+ return font_sizes
187
+
188
+ def _measure_words(self, font_sizes: Dict[str, int]) -> List[WordBox]:
189
+ """Measure word dimensions at their true font sizes"""
190
+ word_boxes = []
191
+ max_freq = max(self.values.values())
192
+
193
+ for word, font_size in font_sizes.items():
194
+ frequency = self.values[word]
195
+ norm_freq = frequency / max_freq
196
+
197
+ # Measure text size
198
+ font = ImageFont.truetype(self.font_path, font_size)
199
+ bbox = font.getbbox(word)
200
+ width = bbox[2] - bbox[0]
201
+ height = bbox[3] - bbox[1]
202
+
203
+ # Get color
204
+ color = self.color_func(word, frequency, norm_freq)
205
+
206
+ word_box = WordBox(
207
+ word=word,
208
+ frequency=frequency,
209
+ font_size=font_size,
210
+ width=width,
211
+ height=height,
212
+ x=0,
213
+ y=0,
214
+ color=color,
215
+ )
216
+ word_boxes.append(word_box)
217
+
218
+ # Sort by size (largest first) for better packing
219
+ word_boxes.sort(key=lambda wb: wb.frequency, reverse=True)
220
+
221
+ return word_boxes
222
+
223
+ def _layout_greedy(self, word_boxes: List[WordBox]) -> List[WordBox]:
224
+ """
225
+ Greedy spiral placement algorithm.
226
+
227
+ Fast and deterministic. Places largest word at center, then spirals
228
+ outward to find non-overlapping positions for remaining words.
229
+ """
230
+ if not word_boxes:
231
+ return []
232
+
233
+ placed_words = []
234
+
235
+ # Place first (largest) word at center
236
+ first_word = word_boxes[0]
237
+ first_word.x = 0
238
+ first_word.y = 0
239
+ placed_words.append(first_word)
240
+
241
+ # Place remaining words using spiral search
242
+ for word_box in word_boxes[1:]:
243
+ position = self._find_position_spiral(word_box, placed_words)
244
+ if position:
245
+ word_box.x, word_box.y = position
246
+ placed_words.append(word_box)
247
+
248
+ return placed_words
249
+
250
+ def _find_position_spiral(
251
+ self, word_box: WordBox, placed_words: List[WordBox]
252
+ ) -> Optional[Tuple[float, float]]:
253
+ """Find a non-overlapping position using spiral search"""
254
+ max_radius = 2000
255
+ radius_step = 5
256
+ angle_step = 30 # degrees
257
+
258
+ for radius in range(0, max_radius, radius_step):
259
+ for angle in range(0, 360, angle_step):
260
+ x = radius * math.cos(math.radians(angle))
261
+ y = radius * math.sin(math.radians(angle))
262
+
263
+ word_box.x = x
264
+ word_box.y = y
265
+
266
+ # Check for overlaps
267
+ has_overlap = False
268
+ for placed_word in placed_words:
269
+ if word_box.overlaps(placed_word, self.margin):
270
+ has_overlap = True
271
+ break
272
+
273
+ if not has_overlap:
274
+ return (x, y)
275
+
276
+ return None
277
+
278
+ def _layout_square(self, word_boxes: List[WordBox]) -> List[WordBox]:
279
+ """
280
+ Center-outward square packing algorithm.
281
+
282
+ Maintains roughly square aspect ratio by trying positions in all
283
+ four directions and choosing the one that keeps layout most square.
284
+ Includes interior gap-filling for compact layouts.
285
+ """
286
+ if not word_boxes:
287
+ return []
288
+
289
+ placed_words = []
290
+
291
+ # Place first (largest) word at center
292
+ first_word = word_boxes[0]
293
+ first_word.x = 0
294
+ first_word.y = 0
295
+ placed_words.append(first_word)
296
+
297
+ # Place remaining words
298
+ for word_box in word_boxes[1:]:
299
+ best_position = None
300
+
301
+ # Calculate current bounding box
302
+ min_x = min(wb.x - wb.width / 2 - self.margin for wb in placed_words)
303
+ max_x = max(wb.x + wb.width / 2 + self.margin for wb in placed_words)
304
+ min_y = min(wb.y - wb.height / 2 - self.margin for wb in placed_words)
305
+ max_y = max(wb.y + wb.height / 2 + self.margin for wb in placed_words)
306
+
307
+ # Try many positions: interior positions first (to fill gaps), then edges
308
+ candidates = []
309
+
310
+ # INTERIOR positions: try a grid throughout the entire bounding box
311
+ step = max(20, int(word_box.width / 2))
312
+ for x in range(int(min_x), int(max_x) + 1, step):
313
+ for y in range(int(min_y), int(max_y) + 1, step):
314
+ pos = self._find_non_overlapping_position(
315
+ word_box, x, y, placed_words
316
+ )
317
+ if pos:
318
+ candidates.append(pos)
319
+
320
+ # RIGHT edge
321
+ x_right = max_x + word_box.width / 2 + self.margin
322
+ for y in range(int(min_y), int(max_y) + 1, 20):
323
+ pos = self._find_non_overlapping_position(
324
+ word_box, x_right, y, placed_words
325
+ )
326
+ if pos:
327
+ candidates.append(pos)
328
+
329
+ # LEFT edge
330
+ x_left = min_x - word_box.width / 2 - self.margin
331
+ for y in range(int(min_y), int(max_y) + 1, 20):
332
+ pos = self._find_non_overlapping_position(
333
+ word_box, x_left, y, placed_words
334
+ )
335
+ if pos:
336
+ candidates.append(pos)
337
+
338
+ # BOTTOM edge
339
+ y_bottom = max_y + word_box.height / 2 + self.margin
340
+ for x in range(int(min_x), int(max_x) + 1, 20):
341
+ pos = self._find_non_overlapping_position(
342
+ word_box, x, y_bottom, placed_words
343
+ )
344
+ if pos:
345
+ candidates.append(pos)
346
+
347
+ # TOP edge
348
+ y_top = min_y - word_box.height / 2 - self.margin
349
+ for x in range(int(min_x), int(max_x) + 1, 20):
350
+ pos = self._find_non_overlapping_position(
351
+ word_box, x, y_top, placed_words
352
+ )
353
+ if pos:
354
+ candidates.append(pos)
355
+
356
+ # Shuffle for randomness
357
+ random.shuffle(candidates)
358
+
359
+ # Evaluate candidates and choose best
360
+ if candidates:
361
+ candidate_metrics = []
362
+ for x, y in candidates:
363
+ new_min_x = min(min_x, x - word_box.width / 2 - self.margin)
364
+ new_max_x = max(max_x, x + word_box.width / 2 + self.margin)
365
+ new_min_y = min(min_y, y - word_box.height / 2 - self.margin)
366
+ new_max_y = max(max_y, y + word_box.height / 2 + self.margin)
367
+
368
+ new_width = new_max_x - new_min_x
369
+ new_height = new_max_y - new_min_y
370
+
371
+ # Squareness metric
372
+ squareness = abs(new_width - new_height)
373
+ distance = (x**2 + y**2) ** 0.5
374
+
375
+ candidate_metrics.append((squareness, distance, x, y))
376
+
377
+ # Find best with tolerance for randomization
378
+ best_squareness = min(m[0] for m in candidate_metrics)
379
+ tolerance = best_squareness * 0.05 + 1.0
380
+
381
+ best_candidates = [
382
+ m for m in candidate_metrics if abs(m[0] - best_squareness) <= tolerance
383
+ ]
384
+
385
+ best_distance = min(m[1] for m in best_candidates)
386
+ distance_tolerance = best_distance * 0.05 + 1.0
387
+
388
+ optimal_candidates = [
389
+ m for m in best_candidates if abs(m[1] - best_distance) <= distance_tolerance
390
+ ]
391
+
392
+ _, _, x, y = random.choice(optimal_candidates)
393
+ best_position = (x, y)
394
+
395
+ if best_position:
396
+ word_box.x, word_box.y = best_position
397
+ placed_words.append(word_box)
398
+
399
+ return placed_words
400
+
401
+ def _find_non_overlapping_position(
402
+ self,
403
+ word_box: WordBox,
404
+ target_x: float,
405
+ target_y: float,
406
+ placed_words: List[WordBox],
407
+ ) -> Optional[Tuple[float, float]]:
408
+ """Try to find a non-overlapping position near the target"""
409
+ word_box.x = target_x
410
+ word_box.y = target_y
411
+
412
+ if not any(self._boxes_overlap(word_box, placed) for placed in placed_words):
413
+ return (target_x, target_y)
414
+
415
+ # Try small adjustments in spiral pattern
416
+ for radius in range(5, 50, 5):
417
+ for angle in range(0, 360, 30):
418
+ x = target_x + radius * math.cos(math.radians(angle))
419
+ y = target_y + radius * math.sin(math.radians(angle))
420
+
421
+ word_box.x = x
422
+ word_box.y = y
423
+
424
+ if not any(self._boxes_overlap(word_box, placed) for placed in placed_words):
425
+ return (x, y)
426
+
427
+ return None
428
+
429
+ def _boxes_overlap(self, box1: WordBox, box2: WordBox) -> bool:
430
+ """Check if two word boxes overlap (including margin)"""
431
+ left1, top1, right1, bottom1 = box1.bbox
432
+ left2, top2, right2, bottom2 = box2.bbox
433
+
434
+ # Expand by margin
435
+ left1 -= self.margin
436
+ top1 -= self.margin
437
+ right1 += self.margin
438
+ bottom1 += self.margin
439
+ left2 -= self.margin
440
+ top2 -= self.margin
441
+ right2 += self.margin
442
+ bottom2 += self.margin
443
+
444
+ return not (right1 <= left2 or right2 <= left1 or bottom1 <= top2 or bottom2 <= top1)
445
+
446
+ def _calculate_bounding_box(
447
+ self, word_boxes: List[WordBox]
448
+ ) -> Tuple[float, float, float, float]:
449
+ """Calculate minimum bounding box containing all words"""
450
+ if not word_boxes:
451
+ return (0, 0, 0, 0)
452
+
453
+ min_x = min(wb.bbox[0] for wb in word_boxes)
454
+ min_y = min(wb.bbox[1] for wb in word_boxes)
455
+ max_x = max(wb.bbox[2] for wb in word_boxes)
456
+ max_y = max(wb.bbox[3] for wb in word_boxes)
457
+
458
+ return (min_x, min_y, max_x, max_y)
459
+
460
+ def generate(self) -> Image.Image:
461
+ """Generate the word cloud image."""
462
+ # Calculate true proportional font sizes
463
+ font_sizes = self._calculate_font_sizes()
464
+
465
+ # Measure words at their true sizes
466
+ word_boxes = self._measure_words(font_sizes)
467
+
468
+ # Layout using selected method
469
+ if self.method == 'greedy':
470
+ print(f"Generating with greedy spiral algorithm...")
471
+ word_boxes = self._layout_greedy(word_boxes)
472
+ else: # square
473
+ print(f"Generating with center-outward square packing...")
474
+ word_boxes = self._layout_square(word_boxes)
475
+
476
+ # Calculate minimum bounding box
477
+ min_x, min_y, max_x, max_y = self._calculate_bounding_box(word_boxes)
478
+
479
+ # Add padding
480
+ padding = 20
481
+ width = int(max_x - min_x) + 2 * padding
482
+ height = int(max_y - min_y) + 2 * padding
483
+
484
+ # Render to image
485
+ image = Image.new("RGB", (width, height), self.background_color)
486
+ draw = ImageDraw.Draw(image)
487
+
488
+ offset_x = -min_x + padding
489
+ offset_y = -min_y + padding
490
+
491
+ for word_box in word_boxes:
492
+ font = ImageFont.truetype(self.font_path, word_box.font_size)
493
+ x = word_box.x - word_box.width / 2 + offset_x
494
+ y = word_box.y - word_box.height / 2 + offset_y
495
+ draw.text((x, y), word_box.word, font=font, fill=word_box.color)
496
+
497
+ return image
498
+
499
+ def generate_with_stats(self) -> Tuple[Image.Image, Dict]:
500
+ """Generate word cloud and return statistics."""
501
+ image = self.generate()
502
+ font_sizes = self._calculate_font_sizes()
503
+
504
+ stats = {
505
+ "num_words": len(self.values),
506
+ "size_range": (min(font_sizes.values()), max(font_sizes.values())),
507
+ "canvas_size": image.size,
508
+ "method": self.method,
509
+ }
510
+
511
+ return image, stats
512
+
513
+
514
+ def main():
515
+ """Test function for TrueWordCloud"""
516
+ print("=" * 70)
517
+ print("TrueWordCloud Test")
518
+ print("=" * 70)
519
+
520
+ values = {
521
+ "python": 100,
522
+ "data": 80,
523
+ "science": 75,
524
+ "visualization": 60,
525
+ "frequency": 50,
526
+ "proportional": 45,
527
+ "word": 40,
528
+ "cloud": 40,
529
+ "layout": 30,
530
+ "algorithm": 25,
531
+ "packing": 20,
532
+ "greedy": 15,
533
+ "dynamic": 10,
534
+ }
535
+
536
+ print(f"\nInput: {len(values)} words")
537
+ print(f"Value range: {min(values.values())} to {max(values.values())}")
538
+
539
+ # Test greedy method
540
+ print("\n" + "=" * 70)
541
+ print("Testing GREEDY method...")
542
+ print("=" * 70)
543
+ twc_greedy = TrueWordCloud(
544
+ values=values,
545
+ method='greedy',
546
+ base_font_size=100,
547
+ min_font_size=10,
548
+ background_color=(255, 255, 255),
549
+ margin=3,
550
+ )
551
+ image, stats = twc_greedy.generate_with_stats()
552
+ image.save("truewordcloud_greedy_test.png")
553
+ print(f"✓ Canvas size: {stats['canvas_size'][0]}×{stats['canvas_size'][1]} pixels")
554
+ print(f"✓ Font range: {stats['size_range'][0]}-{stats['size_range'][1]}pt")
555
+ print(f"✓ Method: {stats['method']}")
556
+ print(f"✓ Saved: truewordcloud_greedy_test.png")
557
+
558
+ # Test square method
559
+ print("\n" + "=" * 70)
560
+ print("Testing SQUARE method...")
561
+ print("=" * 70)
562
+ twc_square = TrueWordCloud(
563
+ values=values,
564
+ method='square',
565
+ base_font_size=100,
566
+ min_font_size=10,
567
+ background_color=(255, 255, 255),
568
+ margin=3,
569
+ )
570
+ image, stats = twc_square.generate_with_stats()
571
+ image.save("truewordcloud_square_test.png")
572
+ print(f"✓ Canvas size: {stats['canvas_size'][0]}×{stats['canvas_size'][1]} pixels")
573
+ print(f"✓ Font range: {stats['size_range'][0]}-{stats['size_range'][1]}pt")
574
+ print(f"✓ Method: {stats['method']}")
575
+ print(f"✓ Saved: truewordcloud_square_test.png")
576
+
577
+
578
+ if __name__ == "__main__":
579
+ main()