Public/New-WordCloud.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
using namespace System.Collections.Generic
using namespace System.Drawing
using namespace System.Management.Automation
using namespace System.Numerics

class SizeTransformAttribute : ArgumentTransformationAttribute {
    static [hashtable] $StandardSizes = @{
        '720p'  = [Size]::new(1280, 720)
        '1080p' = [Size]::new(1920, 1080)
        '4K'    = [Size]::new(4096, 2160)
    }

    [object] Transform([EngineIntrinsics]$engineIntrinsics, [object] $inputData) {
        $Size = switch ($inputData) {
            { $_ -is [Size] } {
                $_
                break
            }
            { $_ -is [SizeF] } {
                $_.ToSize()
                break
            }
            { $_ -is [int] -or $_ -is [double] } {
                [Size]::new($_, $_)
                break
            }
            { $_ -in [SizeTransformAttribute]::StandardSizes.Keys } {
                [SizeTransformAttribute]::StandardSizes[$_]
                break
            }
            { $_ -is [string] } {
                if ($_ -match '^(?<Width>[\d\.,]+)x(?<Height>[\d\.,]+)(px)?$') {
                    [Size]::new($Matches['Width'], $Matches['Height'])
                    break
                }

                if ($_ -match '^(?<Size>[\d\.,]+)(px)?$') {
                    [Size]::new($Matches['Size'], $Matches['Size'])
                    break
                }
            }
            default {
                throw [ArgumentTransformationMetadataException]::new("Unable to convert entered value $inputData to a valid Size.")
            }
        }

        $Area = $Size.Height * $Size.Width
        if ($Area -ge 100 * 100 -and $Area -le 20000 * 20000) {
            return $Size
        }
        else {
            throw [ArgumentTransformationMetadataException]::new(
                "Specified size $inputData is either too small to use for an image size, or would exceed GDI+ limitations."
            )
        }
    }
}

function New-WordCloud {
    <#
    .SYNOPSIS
    Creates a word cloud from the input text.
 
    .DESCRIPTION
    Measures the frequency of use of each word, taking into account plural and similar forms, and creates an image
    with each word's visual size corresponding to the frequency of occurrence in the input text.
 
    .PARAMETER InputString
    The string data to examine and create the word cloud image from.
 
    .PARAMETER Path
    The output path of the word cloud.
 
    .PARAMETER ColorSet
    Define a set of colors to use when rendering the word cloud. Any set of [System.Drawing.KnownColor] values will be
    accepted.
 
    .PARAMETER MaxColors
    Limit the maximum number of colors from either the standard or custom set that will be used. A random selection of
    this many colors will be used to render the word cloud.
 
    .PARAMETER FontFamily
    Specify the font family as a string or [FontFamily] value. System.Drawing supports primarily TrueType fonts.
 
    .PARAMETER FontStyle
    Specify the font style to use for the word cloud.
 
    .PARAMETER ImageSize
    Specify the image size to use in pixels. The image dimensions can be any value between 500 and 20,000px. Any of the
    following size specifier formats are permitted:
 
    - Any valid [System.Drawing.Size] object
    - Any valid [System.Drawing.SizeF] object
    - 1000x1000
    - 1000x1000px
    - 1000
    - 1000px
    - 720p     (Creates an image of size 1280x720px)
    - 1080p (Creates an image of size 1920x1080px)
    - 4K     (Creates an image of size 4096x2160px)
 
    4096x2160 will be used by default. Note that the minimum image resolution is 10,000 pixels (100 x 100px), and the
    maximum resolution is 400,000,000 pixels (20,000 x 20,000px, 400MP).
 
    .PARAMETER DistanceStep
    The number of pixels to increment per radial sweep. Higher values will make the operation quicker, but may reduce
    the effectiveness of the packing algorithm. Lower values will take longer, but will generally ensure a more
    tightly-packed word cloud.
 
    .PARAMETER RadialGranularity
    The number of radial points at each distance step to check during a single sweep. This value is scaled as the radius
    expands to retain some consistency in the overall step distance as the distance from the center increases.
 
    .PARAMETER BackgroundColor
    Set the background color of the image. Colors with similar names to the background color are automatically excluded
    from being selected. Specify $null to render the word cloud on a transparent background.
 
    .PARAMETER Monochrome
    Use only shades of grey to create the word cloud.
 
    .PARAMETER OutputFormat
    Specify the output image file format to use.
 
    .PARAMETER MaxWords
    Specify the maximum number of words to include in the word cloud. 100 is default. If there are fewer unique words
    than the maximum amount, all unique words will be rendered.
 
    .EXAMPLE
    Get-Content .\Words.txt | New-WordCloud -Path .\WordCloud.png
 
    Generates a word cloud from the words in the specified file, and saves it to the specified image file.
 
    .NOTES
    Only the top 100 most frequent words will be included in the word cloud by default; typically, words that fall under
    this ranking end up being impossible to render cleanly except on very high resolutions.
 
    The word cloud will be rendered according to the image size; landscape or portrait configurations will result in
    ovoid clouds, whereas square images will result mainly in circular clouds.
    #>

    [CmdletBinding(DefaultParameterSetName = 'SelectColors')]
    [Alias('wordcloud', 'wcloud')]
    param(
        [Parameter(Mandatory, Position = 0, ValueFromPipeline)]
        [Alias('InputString', 'InputObject', 'String', 'Words', 'Document', 'Page')]
        [AllowEmptyString()]
        [string[]]
        $Text,

        [Parameter(Mandatory, Position = 1)]
        [Alias('OutFile', 'ExportPath', 'ImagePath')]
        [ValidateScript(
            { Test-Path -IsValid $_ -PathType Leaf }
        )]
        [string[]]
        $Path,

        [Parameter(ParameterSetName = 'SelectColors')]
        [Alias('ColourSet')]
        [KnownColor[]]
        $ColorSet = [KnownColor].GetEnumNames(),

        [Parameter()]
        [Alias('MaxColours')]
        [int]
        $MaxColors,

        [Parameter()]
        [Alias('FontFace')]
        [ArgumentCompleter(
            {
                param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParams)
                $FontLibrary = [FontFamily]::Families.Name.Where{-not [string]::IsNullOrWhiteSpace($_)}

                if (!$WordToComplete) {
                    return $FontLibrary -replace '(?="|`|\$)', '`' -replace '^|$', '"'
                }
                else {
                    return $FontLibrary.Where{$_ -match "^$([regex]::Escape($WordToComplete))"} -replace '(?="|`|\$)', '`' -replace '^|$', '"'
                }
            }
        )]
        [FontFamily]
        $FontFamily = [FontFamily]::new('Consolas'),

        [Parameter()]
        [FontStyle]
        $FontStyle = [FontStyle]::Regular,

        [Parameter()]
        [Alias('ImagePixelSize')]
        [ArgumentCompleter(
            {
                param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParams)

                $Values = @('720p', '1080p', '4K', '640x1146', '480x800')

                if ($WordToComplete) {
                    return $Values.Where{$_ -match "^$WordToComplete"}
                }
                else {
                    return $Values
                }
            }
        )]
        [SizeTransformAttribute()]
        [Size]
        $ImageSize = [Size]::new(4096, 2160),

        [Parameter()]
        [ValidateRange(1, 500)]
        $DistanceStep = 5,

        [Parameter()]
        [ValidateRange(1, 50)]
        $RadialGranularity = 15,

        [Parameter()]
        [Alias('BackgroundColour')]
        [Nullable[KnownColor]]
        $BackgroundColor = [KnownColor]::Black,

        [Parameter(Mandatory, ParameterSetName = 'Monochrome')]
        [Alias('Greyscale', 'Grayscale')]
        [switch]
        $Monochrome,

        [Parameter()]
        [Alias('ImageFormat', 'Format')]
        [ValidateSet("Bmp", "Emf", "Exif", "Gif", "Jpeg", "Png", "Tiff", "Wmf")]
        [string]
        $OutputFormat = "Png",

        [Parameter()]
        [Alias('MaxWords')]
        [ValidateRange(10, 500)]
        [int]
        $MaxUniqueWords = 100
    )
    begin {
        $ExcludedWords = @(
            'a', 'about', 'above', 'after', 'again', 'against', 'all', 'also', 'am', 'an', 'and', 'any', 'are', 'aren''t', 'as',
            'at', 'be', 'because', 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by', 'can', 'can''t',
            'cannot', 'com', 'could', 'couldn''t', 'did', 'didn''t', 'do', 'does', 'doesn''t', 'doing', 'don''t', 'down',
            'during', 'each', 'else', 'ever', 'few', 'for', 'from', 'further', 'get', 'had', 'hadn''t', 'has', 'hasn''t',
            'have', 'haven''t', 'having', 'he', 'he''d', 'he''ll', 'he''s', 'hence', 'her', 'here', 'here''s', 'hers',
            'herself', 'him', 'himself', 'his', 'how', 'how''s', 'however', 'http', 'i', 'i''d', 'i''ll', 'i''m', 'i''ve', 'if',
            'in', 'into', 'is', 'isn''t', 'it', 'it''s', 'its', 'itself', 'just', 'k', 'let''s', 'like', 'me', 'more', 'most',
            'mustn''t', 'my', 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'or', 'other', 'otherwise',
            'ought', 'our', 'ours', 'ourselves', 'out', 'over', 'own', 'r', 'same', 'shall', 'shan''t', 'she', 'she''d',
            'she''ll', 'she''s', 'should', 'shouldn''t', 'since', 'so', 'some', 'such', 'than', 'that', 'that''s', 'the',
            'their', 'theirs', 'them', 'themselves', 'then', 'there', 'there''s', 'therefore', 'these', 'they', 'they''d',
            'they''ll', 'they''re', 'they''ve', 'this', 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was',
            'wasn''t', 'we', 'we''d', 'we''ll', 'we''re', 'we''ve', 'were', 'weren''t', 'what', 'what''s', 'when', 'when''s',
            'where', 'where''s', 'which', 'while', 'who', 'who''s', 'whom', 'why', 'why''s', 'with', 'won''t', 'would',
            'wouldn''t', 'www', 'you', 'you''d', 'you''ll', 'you''re', 'you''ve', 'your', 'yours', 'yourself', 'yourselves'
        ) -join '|'
        $SplitChars = " `n.,`"?!{}[]:()`“`”™" -as [char[]]
        $ColorIndex = 0
        $RadialDistance = 0

        $WordList = [List[string]]::new()
        $WordHeightTable = @{}
        $WordSizeTable = @{}

        $ExportFormat = $OutputFormat | Get-ImageFormat

        if ($PSCmdlet.ParameterSetName -eq 'Monochrome') {
            $MinSaturation = 0
        }
        else {
            $MinSaturation = 0.5
        }

        if (-not $PSBoundParameters.ContainsKey('MaxColors')) {
            $MaxColors = [int]::MaxValue
        }

        $PathList = foreach ($FilePath in $Path) {
            if ($FilePath -notmatch "\.$OutputFormat$") {
                $FilePath += $OutputFormat
            }
            if (-not (Test-Path -Path $FilePath)) {
                (New-Item -ItemType File -Path $FilePath).FullName
            }
            else {
                (Get-Item -Path $FilePath).FullName
            }
        }

        $ColorList = $ColorSet |
            Sort-Object {Get-Random} |
            Select-Object -First $MaxColors |
            ForEach-Object {
            if (-not $Monochrome) {
                [Color]::FromKnownColor($_)
            }
            else {
                [int]$Brightness = [Color]::FromKnownColor($_).GetBrightness() * 255
                [Color]::FromArgb($Brightness, $Brightness, $Brightness)
            }
        } |
            Where-Object {
            if ($BackgroundColor) {
                $_.Name -notmatch $BackgroundColor -and
                $_.GetSaturation() -ge $MinSaturation
            }
            else {
                $_.GetSaturation() -ge $MinSaturation
            }
        } |
            Sort-Object -Descending {
            $Value = $_.GetBrightness()
            $Random = (-$Value..$Value | Get-Random) / (1 - $_.GetSaturation())
            $Value + $Random
        }
    }
    process {
        $WordList.AddRange(
            $Text.Split($SplitChars, [StringSplitOptions]::RemoveEmptyEntries).Where{
                $_ -notmatch "^($ExcludedWords)s?$|^[^a-z]+$|[^a-z0-9'_-]" -and $_.Length -gt 1
            } -replace "^'|'$" -as [string[]]
        )
    }
    end {
        # Count occurrence of each word
        switch ($WordList) {
            { $WordHeightTable[($_ -replace 's$')] } {
                $WordHeightTable[($_ -replace 's$')] ++
                continue
            }
            { $WordHeightTable["${_}s"] } {
                $WordHeightTable[$_] = $WordHeightTable["${_}s"] + 1
                $WordHeightTable.Remove("${_}s")
                continue
            }
            default {
                $WordHeightTable[$_] ++
                continue
            }
        }

        $SortedWordList = $WordHeightTable.GetEnumerator().Name |
            Sort-Object -Descending { $WordHeightTable[$_] } |
            Select-Object -First $MaxUniqueWords

        $HighestFrequency, $AverageFrequency = $SortedWordList |
            ForEach-Object { $WordHeightTable[$_] } |
            Measure-Object -Average -Maximum |
            ForEach-Object {$_.Maximum, $_.Average}

        $FontScale = ($ImageSize.Height + $ImageSize.Width) / ($AverageFrequency * $SortedWordList.Count)

        try {
            # Create a graphics object to measure the text's width and height.
            $DummyImage = [Bitmap]::new(1, 1)
            $Graphics = [Graphics]::FromImage($DummyImage)

            foreach ($Word in $SortedWordList) {
                $WordHeightTable[$Word] = [Math]::Round($WordHeightTable[$Word] * $FontScale)
                if ($WordHeightTable[$Word] -lt 8) { continue }

                $Font = [Font]::new(
                    $FontFamily,
                    $WordHeightTable[$Word],
                    $FontStyle,
                    [GraphicsUnit]::Pixel
                )

                $WordSizeTable[$Word] = $Graphics.MeasureString($Word, $Font)
            }

            $WordHeightTable | Out-String | Write-Debug
        }
        catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
        finally {
            if ($Graphics) {
                $Graphics.Dispose()
            }
            if ($DummyImage) {
                $DummyImage.Dispose()
            }
        }

        $MaxSideLength = [Math]::Max($ImageSize.Width, $ImageSize.Height)
        $GCD = Get-GreatestCommonDivisor -Numerator $MaxSideLength -Denominator ([Math]::Min($ImageSize.Width, $ImageSize.Height))
        $AspectRatio = $ImageSize.Width / $ImageSize.Height
        $CentrePoint = [PointF]::new($ImageSize.Width / 2, $ImageSize.Height / 2)

        [PSCustomObject]@{
            ExportFormat     = $ExportFormat
            UniqueWords      = $WordHeightTable.GetEnumerator().Name.Count
            HighestFrequency = $HighestFrequency
            AverageFrequency = $AverageFrequency
            MaxFontSize      = $HighestFrequency * $FontScale
            ImageSize        = $ImageSize
            ImageCentre      = $CentrePoint
            AspectRatio      = "$($ImageSize.Width / $GCD) : $($ImageSize.Height / $GCD)"
            FontFamily       = $FontFamily
        } | Format-List | Out-String | Write-Verbose

        try {
            $WordCloudImage = [Bitmap]::new($ImageSize.Width, $ImageSize.Height)
            [Graphics]$DrawingSurface = [Graphics]::FromImage($WordCloudImage)

            if ($BackgroundColor) {
                $DrawingSurface.Clear([Color]::FromKnownColor($BackgroundColor))
            }
            $DrawingSurface.SmoothingMode = [Drawing2D.SmoothingMode]::AntiAlias
            $DrawingSurface.TextRenderingHint = [Text.TextRenderingHint]::AntiAlias

            $RectangleList = [List[RectangleF]]::new()
            $RadialScanCount = 0
            $Jitter = [Random]::new()
            :words foreach ($Word in $SortedWordList) {
                if (-not $WordSizeTable[$Word]) { continue }

                $Font = [Font]::new(
                    $FontFamily,
                    $WordHeightTable[$Word],
                    $FontStyle,
                    [GraphicsUnit]::Pixel
                )

                $RadialScanCount /= 3
                $WordRectangle = $null
                do {
                    if ( $RadialDistance -gt ($MaxSideLength / 2) ) {
                        $RadialDistance = $MaxSideLength / $DistanceStep / 25
                        continue words
                    }

                    $AngleIncrement = 360 / ( ($RadialDistance + 1) * $RadialGranularity / 10 )
                    switch ([int]$RadialScanCount -band 7) {
                        0 { $Start = 0; $End = 360 }
                        1 { $Start = -90; $End = 270 }
                        2 { $Start = -180; $End = 180 }
                        3 { $Start = -270; $End = 90  }
                        4 { $Start = 360; $End = 0; $AngleIncrement *= -1 }
                        5 { $Start = 270; $End = -90; $AngleIncrement *= -1 }
                        6 { $Start = 180; $End = -180; $AngleIncrement *= -1 }
                        7 { $Start = 90; $End = -270; $AngleIncrement *= -1 }
                    }

                    $IsColliding = $false
                    for (
                        $Angle = $Start;
                        $( if ($Start -lt $End) {$Angle -le $End} else {$End -le $Angle} );
                        $Angle += $AngleIncrement
                    ) {
                        $Radians = Convert-ToRadians -Degrees $Angle
                        $Complex = [Complex]::FromPolarCoordinates($RadialDistance, $Radians)

                        if ($WordHeightTable[$Word] -ne $HighestFrequency * $FontScale -and $AspectRatio -lt 1) {
                            $OffsetX = $WordSizeTable[$Word].Width * $Jitter.NextDouble()
                            $OffsetY = $WordSizeTable[$Word].Height * $Jitter.NextDouble()
                        }
                        $DrawLocation = [PointF]::new(
                            $Complex.Real * $AspectRatio + $CentrePoint.X - $OffsetX,
                            $Complex.Imaginary + $CentrePoint.Y - $OffsetY
                        )

                        $WordRectangle = [RectangleF]::new([PointF]$DrawLocation, [SizeF]$WordSizeTable[$Word])

                        foreach ($Rectangle in $RectangleList) {
                            $IsColliding = (
                                $WordRectangle.IntersectsWith($Rectangle) -or
                                $WordRectangle.Top -lt 0 -or
                                $WordRectangle.Left -lt 0 -or
                                $WordRectangle.Bottom -gt $ImageSize.Height -or
                                $WordRectangle.Right -gt $ImageSize.Width
                            )

                            if ($IsColliding) {
                                break
                            }
                        }

                        if (!$IsColliding) {
                            break
                        }
                    }

                    if ($IsColliding) {
                        $RadialDistance += $DistanceStep
                        $RadialScanCount++
                    }
                } while ($IsColliding)

                $RectangleList.Add($WordRectangle)
                $Color = $ColorList[$ColorIndex]

                $ColorIndex++
                if ($ColorIndex -ge $ColorList.Count) {
                    $ColorIndex = 0
                }

                Write-Debug "Writing $Word with font $Font in $Color at $DrawLocation"
                $DrawingSurface.DrawString($Word, $Font, [SolidBrush]::new($Color), $DrawLocation)

                $RadialDistance -= $DistanceStep * ($RadialScanCount / 2)
            }

            $DrawingSurface.Flush()
            foreach ($FilePath in $PathList) {
                $WordCloudImage.Save($FilePath, $ExportFormat)
            }
        }
        catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
        finally {
            $DrawingSurface.Dispose()
            $WordCloudImage.Dispose()
        }
    }
}