Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Зиновьева Милана #13

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ bld/
msbuild.log
msbuild.err
msbuild.wrn
FractalPainter/
21 changes: 21 additions & 0 deletions ConsoleClient/ConsoleClient.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Autofac" Version="8.2.0" />
<PackageReference Include="CommandLineParser" Version="2.5.0" />
<PackageReference Include="System.ComponentModel.Composition" Version="4.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../DrawingTagsCloudVisualization/DrawingTagsCloudVisualization.csproj" />
<ProjectReference Include="../TagsCloudVisualization/TagsCloudVisualization.csproj" />
</ItemGroup>

</Project>
72 changes: 72 additions & 0 deletions ConsoleClient/DependencyInjectionConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System.Drawing;
using System.Runtime.InteropServices;
using Autofac;
using DrawingTagsCloudVisualization;
using TagsCloudVisualization;
using TagsCloudVisualization.FilesProcessing;
using TagsCloudVisualization.ManagingRendering;

namespace ConsoleClient;

public static class DependencyInjectionConfig
{
public static IContainer BuildContainer(Options options)
{
var builder = new ContainerBuilder();
var pathToMystem = "";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
pathToMystem = "mystem.exe";
else
pathToMystem = "mystem";
builder.RegisterInstance(new MyStemWrapper.MyStem
{
PathToMyStem = pathToMystem,
Parameters = "-ni"
}).As<MyStemWrapper.MyStem>().SingleInstance();

builder.RegisterType<MorphologicalProcessing>()
.As<IMorphologicalAnalyzer>()
.InstancePerDependency();

builder.RegisterType<TxtFileProcessor>()
.As<IFileProcessor>()
.InstancePerDependency();

builder.Register<ISpiral>(c =>
{
var centerPoint = new Point(options.CenterX, options.CenterY);
return options.AlgorithmForming switch
{
"Circle" => new ArchimedeanSpiral(centerPoint, 1),
_ => new FermatSpiral(centerPoint, 20),
};
}).As<ISpiral>().InstancePerDependency();

builder.RegisterType<WordHandler>()
.As<IWordHandler>()
.InstancePerDependency();
builder.RegisterType<RectangleGenerator>()
.As<IRectangleGenerator>()
.InstancePerDependency();
builder.RegisterType<TagsCloudDrawingFacade>()
.As<ITagsCloudDrawingFacade>()
.InstancePerDependency();

switch (options.AlgorithmDrawing)
{
case "Altering":
builder.RegisterType<AlternatingColorsTagsCloudDrawer>().As<ITagsCloudDrawer>()
.InstancePerDependency();
break;
default:
builder.RegisterType<StandartTagsCloudDrawer>().As<ITagsCloudDrawer>()
.InstancePerDependency();
break;
}
builder.RegisterType<ImageSaver>()
.As<IImageSaver>()
.InstancePerDependency();

return builder.Build();
}
}
39 changes: 39 additions & 0 deletions ConsoleClient/Examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# 1 example:

Agrs: dotnet run
![alt text](example.png)

# 2 example:

Args: dotnet run -- -o Examples/example1.png -l 500 -w 500
![alt text](example1.png)

# 3 example:

Args: dotnet run -- -o Examples/example2.png -x 150 -y 300
![alt text](example2.png)

# 4 example:

Args: dotnet run -- -c pink -o Examples/example3.png
![alt text](example3.png)

# 5 example:

Args: dotnet run -- -a Fermat -o Examples/example4.png
![alt text](example4.png)

# 6 example:

Args: dotnet run -- -p S -o Examples/example5.png
![alt text](example5.png)

# 7 example:

Args: dotnet run -- -d Altering -o Examples/example7.png
![alt text](example7.png)

# 8 example:

Args: dotnet run -- -p A,V -o Examples/example8.png -i Examples/example1.txt
![alt text](example8.png)
Binary file added ConsoleClient/Examples/example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions ConsoleClient/Examples/example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
да
о
кошка
кошка
большой
большой
большой
дом
дом
красиво
красиво
красиво
красиво
и
книга
книга
азбука
азбука
кружка
кружка
кружка
алгебра
алгебра
алгебра
носок
носок
не
Binary file added ConsoleClient/Examples/example1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 49 additions & 0 deletions ConsoleClient/Examples/example1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
да
о
кошка
кошка
большой
большой
большой
дом
дом
дом
красиво
красиво
красиво
красиво
и
книга
книга
азбука
азбука
кружка
кружка
кружка
алгебра
алгебра
алгебра
носок
носок
носок
не
говно
говно
говно
хуй
хуй
хуй
залупа
залупа
мошонник
мошонник
мошонник
мошонник
говнохуй
говнохуй
говнохуй
говнохуй
влиять
влиять
бегать
бегать
Binary file added ConsoleClient/Examples/example2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example7.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example8.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions ConsoleClient/ITagsCloudDrawingFacade.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace ConsoleClient;
public interface ITagsCloudDrawingFacade
{
void DrawRectangle(Options options);
}
35 changes: 35 additions & 0 deletions ConsoleClient/Options.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using CommandLine;
namespace ConsoleClient;

public class Options
{
[Option('i', "input", Default = "Examples/example.txt", HelpText = "Путь к входному текстовому файлу.")]
public required string InputFilePath { get; set; }

[Option('o', "output", Default = "Examples/example.png", HelpText = "Путь к выходному изображению.")]
public required string OutputFilePath { get; set; }

[Option('x', "centerX", Default = 200, HelpText = "Координата X центра.")]
public int CenterX { get; set; }

[Option('y', "centerY", Default = 200, HelpText = "Координата Y центра.")]
public int CenterY { get; set; }

[Option('l', "length", Default = 400, HelpText = "Длина изображения")]
public int Length { get; set; }

[Option('w', "width", Default = 400, HelpText = "Ширина изображения")]
public int Width{ get; set; }

[Option('c', "color", Default = "black", HelpText = "Цвет текста")]
public string Color{ get; set; }

[Option('a', "algorithmf", Default = "Circle", HelpText = "Алгоритм формирования(квадрат, круг)")]
public string AlgorithmForming{ get; set; }

[Option('p', "excludedpartofspeech", Required = false, HelpText = "Исключить часть речи S V A ADV NUM SPRO ANUM ADVPRO")]
public string ExcludedPartOfSpeech{ get; set; }

[Option('d', "algorithmd", Default = "Standart", HelpText = "Алгоритм рисования(Standart, Altering)")]
public string AlgorithmDrawing{ get; set; }
}
81 changes: 81 additions & 0 deletions ConsoleClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using Autofac;
using CommandLine;

namespace ConsoleClient;


public class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed(RunApplication)
.WithNotParsed(HandleErrors);
}
readonly static private HashSet<string> validPartsOfSpeech =
[
"S", "V", "A", "ADV", "NUM", "SPRO", "ADVPRO", "ANUM"
];

private static void RunApplication(Options options)
{
if (options.AlgorithmForming != "Circle" && options.AlgorithmForming != "Fermat")
{
Console.WriteLine($"Ошибка: Неизвестный алгоритм '{options.AlgorithmForming}'. Допустимые значения: 'Circle', 'Fermat'.");
return;
}
if (!string.IsNullOrEmpty(options.ExcludedPartOfSpeech))
{
var excludedParts = options.ExcludedPartOfSpeech.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Trim().ToUpper());

var invalidParts = excludedParts.Where(part => !validPartsOfSpeech.Contains(part)).ToList();

if (invalidParts.Count != 0)
{
Console.WriteLine($"Ошибка: Неизвестные части речи '{string.Join(", ", invalidParts)}'");
return;
}
}
if (options.AlgorithmDrawing != "Standart" && options.AlgorithmDrawing != "Altering")
{
Console.WriteLine($"Ошибка: Неизвестный алгоритм рассказки '{options.AlgorithmDrawing}'");
return;
}
var container = DependencyInjectionConfig.BuildContainer(options);

using var scope = container.BeginLifetimeScope();
try
{
scope.Resolve<ITagsCloudDrawingFacade>().DrawRectangle(options);
Console.WriteLine($"Облако тегов успешно сохранено в файл: {options.OutputFilePath}");
}
catch (Exception ex)
{
Console.WriteLine($"Произошла ошибка: {ex.Message}");
}
}

private static void HandleErrors(IEnumerable<Error> errors)
{
Console.WriteLine("Ошибка при обработке аргументов командной строки.");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот тут бы обработать коллекцию ошибок, чтобы пользователя не оставить в недоумении

foreach (var error in errors)
{
switch (error)
{
case UnknownOptionError unknownOptionError:
Console.WriteLine($"- Неизвестный параметр: {unknownOptionError.Token}");
break;
case SetValueExceptionError setValueExceptionError:
Console.WriteLine($"- Ошибка установки значения: {setValueExceptionError.Exception.Message}");
break;
case MissingValueOptionError missingValueOptionError:
Console.WriteLine($"- Отсутствует значение: {missingValueOptionError.NameInfo}");
break;
default:
Console.WriteLine($"- Неизвестная ошибка: {error.GetType().Name}");
break;
}
}
}
}
20 changes: 20 additions & 0 deletions ConsoleClient/TagsCloudDrawingFacade.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.Drawing;
using DrawingTagsCloudVisualization;
using TagsCloudVisualization;
namespace ConsoleClient;

public class TagsCloudDrawingFacade(
IWordHandler wordHandler,
IRectangleGenerator rectangleGenerator, IImageSaver imageSaver) : ITagsCloudDrawingFacade
{
private readonly IWordHandler _wordHandler = wordHandler;
private readonly IRectangleGenerator _rectangleGenerator = rectangleGenerator;
private readonly IImageSaver _imageSaver = imageSaver;

public void DrawRectangle(Options options)
{
var frequencyRectangles = _wordHandler.ProcessFile(options.InputFilePath, options.ExcludedPartOfSpeech);
var arrRect = _rectangleGenerator.ExecuteRectangles(frequencyRectangles, new Point(options.CenterX, options.CenterY));
_imageSaver.SaveToFile(options.OutputFilePath, options.Length, options.Width, options.Color, arrRect);
}
}
Binary file added ConsoleClient/mystem
Binary file not shown.
Binary file added ConsoleClient/mystem.exe
Binary file not shown.
Loading