-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProgram.cs
More file actions
80 lines (73 loc) · 2.9 KB
/
Program.cs
File metadata and controls
80 lines (73 loc) · 2.9 KB
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
using KnowledgePicker.WordCloud;
using KnowledgePicker.WordCloud.Coloring;
using KnowledgePicker.WordCloud.Drawing;
using KnowledgePicker.WordCloud.Layouts;
using KnowledgePicker.WordCloud.Primitives;
using KnowledgePicker.WordCloud.Sizers;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace WordFrequency.ConsoleApp
{
class Program
{
static int Main(string[] args)
{
var command = new RootCommand
{
new Argument<FileInfo>("output",
() => new FileInfo(Path.Join(Environment.CurrentDirectory, "output.png")),
"Path to the output file, default is `output.png`.")
};
command.Description = "Takes words on input and generates word cloud as PNG from them.";
command.Handler = CommandHandler.Create<FileInfo>(output =>
{
// Process words on input.
var freqs = new Dictionary<string, int>();
var whitespaces = new Regex(@"\s+");
while (Console.ReadLine() is string line)
{
foreach (var word in whitespaces.Split(line))
{
if (!freqs.TryGetValue(word, out var freq))
{
freq = 0;
}
freqs[word] = freq + 1;
}
}
// Generate topic cloud.
const int k = 4; // scale
var wordCloud = new WordCloudInput(
freqs.Select(p => new WordCloudEntry(p.Key, p.Value)))
{
Width = 1024 * k,
Height = 256 * k,
MinFontSize = 8 * k,
MaxFontSize = 32 * k
};
var sizer = new LogSizer(wordCloud);
using var engine = new SkGraphicEngine(sizer, wordCloud);
var layout = new SpiralLayout(wordCloud);
var colorizer = new RandomColorizer(); // optional
var wcg = new WordCloudGenerator<SKBitmap>(wordCloud, engine, layout, colorizer);
// Draw the bitmap on white background.
using var final = new SKBitmap(wordCloud.Width, wordCloud.Height);
using var canvas = new SKCanvas(final);
canvas.Clear(SKColors.White);
using var bitmap = wcg.Draw();
canvas.DrawBitmap(bitmap, 0, 0);
// Save to PNG.
using var data = final.Encode(SKEncodedImageFormat.Png, 100);
using var writer = output.Create();
data.SaveTo(writer);
});
return command.Invoke(args);
}
}
}