Repository: the-database/MangaJaNaiConverterGui Branch: main Commit: e63e7843ba45 Files: 136 Total size: 971.0 KB Directory structure: gitextract_o6l0qlog/ ├── .editorconfig ├── .github/ │ └── workflows/ │ └── deploy.yml ├── .gitignore ├── LICENSE ├── MangaJaNaiConverterGui/ │ ├── App.axaml │ ├── App.axaml.cs │ ├── Drivers/ │ │ └── NewtonsoftJsonSuspensionDriver.cs │ ├── MangaJaNaiConverterGui.csproj │ ├── Program.cs │ ├── Services/ │ │ ├── Downloader.cs │ │ ├── ETACalculator.cs │ │ ├── IPythonService.cs │ │ ├── ISuspensionDriverService.cs │ │ ├── IUpdateManagerService.cs │ │ ├── PythonService.cs │ │ ├── SuspensionDriverService.cs │ │ └── UpdateManagerService.cs │ ├── ViewLocator.cs │ ├── ViewModels/ │ │ ├── MainWindowViewModel.cs │ │ └── ViewModelBase.cs │ ├── Views/ │ │ ├── MainWindow.axaml │ │ └── MainWindow.axaml.cs │ ├── app.manifest │ ├── appstate2.json │ └── backend/ │ ├── ImageMagick/ │ │ ├── Custom Gray Gamma 1.0.icc │ │ ├── Custom RGB Gamma 1.0.icc │ │ └── Dot Gain 20%.icc │ ├── resources/ │ │ └── default_cli_configuration.json │ └── src/ │ ├── .pre-commit-config.yaml │ ├── README.md │ ├── __init__.py │ ├── accelerator_detection.py │ ├── api/ │ │ ├── __init__.py │ │ ├── api.py │ │ ├── group.py │ │ ├── input.py │ │ ├── iter.py │ │ ├── lazy.py │ │ ├── node_check.py │ │ ├── node_context.py │ │ ├── node_data.py │ │ ├── output.py │ │ ├── settings.py │ │ └── types.py │ ├── device_list.py │ ├── gpu.py │ ├── navi.py │ ├── nodes/ │ │ ├── __init__.py │ │ ├── condition.py │ │ ├── group.py │ │ ├── groups.py │ │ ├── impl/ │ │ │ ├── __init__.py │ │ │ ├── blend.py │ │ │ ├── color/ │ │ │ │ ├── __init__.py │ │ │ │ ├── color.py │ │ │ │ ├── convert.py │ │ │ │ ├── convert_data.py │ │ │ │ └── convert_model.py │ │ │ ├── image_formats.py │ │ │ ├── image_op.py │ │ │ ├── image_utils.py │ │ │ ├── onnx/ │ │ │ │ ├── __init__.py │ │ │ │ ├── auto_split.py │ │ │ │ ├── load.py │ │ │ │ ├── model.py │ │ │ │ ├── np_tensor_utils.py │ │ │ │ ├── onnx_to_ncnn.py │ │ │ │ ├── session.py │ │ │ │ ├── tensorproto_utils.py │ │ │ │ ├── update_model_dims.py │ │ │ │ └── utils.py │ │ │ ├── pil_utils.py │ │ │ ├── pytorch/ │ │ │ │ ├── __init__.py │ │ │ │ ├── auto_split.py │ │ │ │ ├── convert_to_onnx_impl.py │ │ │ │ ├── pix_transform/ │ │ │ │ │ ├── LICENSE │ │ │ │ │ ├── auto_split.py │ │ │ │ │ ├── pix_transform.py │ │ │ │ │ └── pix_transform_net.py │ │ │ │ ├── rife/ │ │ │ │ │ ├── IFNet_HDv3_v4_14_align.py │ │ │ │ │ └── warplayer.py │ │ │ │ └── utils.py │ │ │ ├── resize.py │ │ │ └── upscale/ │ │ │ ├── __init__.py │ │ │ ├── auto_split.py │ │ │ ├── auto_split_tiles.py │ │ │ ├── basic_upscale.py │ │ │ ├── convenient_upscale.py │ │ │ ├── custom_scale.py │ │ │ ├── exact_split.py │ │ │ ├── grayscale.py │ │ │ ├── passthrough.py │ │ │ ├── tile_blending.py │ │ │ └── tiler.py │ │ ├── node_cache.py │ │ ├── properties/ │ │ │ ├── __init__.py │ │ │ ├── inputs/ │ │ │ │ ├── __init__.py │ │ │ │ ├── __system_inputs.py │ │ │ │ ├── file_inputs.py │ │ │ │ ├── generic_inputs.py │ │ │ │ ├── image_dropdown_inputs.py │ │ │ │ ├── label.py │ │ │ │ ├── ncnn_inputs.py │ │ │ │ ├── numeric_inputs.py │ │ │ │ ├── numpy_inputs.py │ │ │ │ ├── onnx_inputs.py │ │ │ │ └── pytorch_inputs.py │ │ │ └── outputs/ │ │ │ ├── __init__.py │ │ │ ├── file_outputs.py │ │ │ ├── generic_outputs.py │ │ │ ├── ncnn_outputs.py │ │ │ ├── numpy_outputs.py │ │ │ ├── onnx_outputs.py │ │ │ └── pytorch_outputs.py │ │ └── utils/ │ │ ├── __init__.py │ │ ├── format.py │ │ ├── seed.py │ │ └── utils.py │ ├── packages/ │ │ └── chaiNNer_pytorch/ │ │ ├── __init__.py │ │ ├── pytorch/ │ │ │ ├── __init__.py │ │ │ ├── io/ │ │ │ │ └── load_model.py │ │ │ └── processing/ │ │ │ └── upscale_image.py │ │ └── settings.py │ ├── progress_controller.py │ ├── pyproject.toml │ ├── pyrightconfig.json │ ├── run_upscale.py │ ├── spandrel_custom/ │ │ ├── __init__.py │ │ └── architectures/ │ │ └── FDAT/ │ │ ├── __arch/ │ │ │ ├── LICENSE │ │ │ └── fdat.py │ │ └── __init__.py │ ├── system.py │ └── test_accelerators.py ├── MangaJaNaiConverterGui.sln ├── README.md └── pack.bat ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # Remove the line below if you want to inherit .editorconfig settings from higher directories root = true # C# files [*.cs] #### Core EditorConfig Options #### # Indentation and spacing indent_size = 4 indent_style = space tab_width = 4 # New line preferences end_of_line = crlf insert_final_newline = false #### .NET Coding Conventions #### # Organize usings dotnet_separate_import_directive_groups = false dotnet_sort_system_directives_first = false file_header_template = unset # this. and Me. preferences dotnet_style_qualification_for_event = false dotnet_style_qualification_for_field = false dotnet_style_qualification_for_method = false dotnet_style_qualification_for_property = false # Language keywords vs BCL types preferences dotnet_style_predefined_type_for_locals_parameters_members = true dotnet_style_predefined_type_for_member_access = true # Parentheses preferences dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity dotnet_style_parentheses_in_other_binary_operators = always_for_clarity dotnet_style_parentheses_in_other_operators = never_if_unnecessary dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity # Modifier preferences dotnet_style_require_accessibility_modifiers = for_non_interface_members # Expression-level preferences dotnet_style_coalesce_expression = true dotnet_style_collection_initializer = true dotnet_style_explicit_tuple_names = true dotnet_style_namespace_match_folder = true dotnet_style_null_propagation = true dotnet_style_object_initializer = true dotnet_style_operator_placement_when_wrapping = beginning_of_line dotnet_style_prefer_auto_properties = true dotnet_style_prefer_collection_expression = when_types_loosely_match dotnet_style_prefer_compound_assignment = true dotnet_style_prefer_conditional_expression_over_assignment = true dotnet_style_prefer_conditional_expression_over_return = true dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed dotnet_style_prefer_inferred_anonymous_type_member_names = true dotnet_style_prefer_inferred_tuple_names = true dotnet_style_prefer_is_null_check_over_reference_equality_method = true dotnet_style_prefer_simplified_boolean_expressions = true dotnet_style_prefer_simplified_interpolation = true # Field preferences dotnet_style_readonly_field = true # Parameter preferences dotnet_code_quality_unused_parameters = all # Suppression preferences dotnet_remove_unnecessary_suppression_exclusions = none # New line preferences dotnet_style_allow_multiple_blank_lines_experimental = true dotnet_style_allow_statement_immediately_after_block_experimental = true #### C# Coding Conventions #### # var preferences csharp_style_var_elsewhere = false csharp_style_var_for_built_in_types = false csharp_style_var_when_type_is_apparent = false # Expression-bodied members csharp_style_expression_bodied_accessors = true csharp_style_expression_bodied_constructors = false csharp_style_expression_bodied_indexers = true csharp_style_expression_bodied_lambdas = true csharp_style_expression_bodied_local_functions = false csharp_style_expression_bodied_methods = false csharp_style_expression_bodied_operators = false csharp_style_expression_bodied_properties = true # Pattern matching preferences csharp_style_pattern_matching_over_as_with_null_check = true csharp_style_pattern_matching_over_is_with_cast_check = true csharp_style_prefer_extended_property_pattern = true csharp_style_prefer_not_pattern = true csharp_style_prefer_pattern_matching = true csharp_style_prefer_switch_expression = true # Null-checking preferences csharp_style_conditional_delegate_call = true # Modifier preferences csharp_prefer_static_local_function = true csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async csharp_style_prefer_readonly_struct = true csharp_style_prefer_readonly_struct_member = true # Code-block preferences csharp_prefer_braces = true csharp_prefer_simple_using_statement = true csharp_style_namespace_declarations = block_scoped csharp_style_prefer_method_group_conversion = true csharp_style_prefer_primary_constructors = true csharp_style_prefer_top_level_statements = true # Expression-level preferences csharp_prefer_simple_default_expression = true csharp_style_deconstructed_variable_declaration = true csharp_style_implicit_object_creation_when_type_is_apparent = true csharp_style_inlined_variable_declaration = true csharp_style_prefer_index_operator = true csharp_style_prefer_local_over_anonymous_function = true csharp_style_prefer_null_check_over_type_check = true csharp_style_prefer_range_operator = true csharp_style_prefer_tuple_swap = true csharp_style_prefer_utf8_string_literals = true csharp_style_throw_expression = true csharp_style_unused_value_assignment_preference = discard_variable csharp_style_unused_value_expression_statement_preference = discard_variable # 'using' directive preferences csharp_using_directive_placement = outside_namespace # New line preferences csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true csharp_style_allow_embedded_statements_on_same_line_experimental = true #### C# Formatting Rules #### # New line preferences csharp_new_line_before_catch = true csharp_new_line_before_else = true csharp_new_line_before_finally = true csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_open_brace = all csharp_new_line_between_query_expression_clauses = true # Indentation preferences csharp_indent_block_contents = true csharp_indent_braces = false csharp_indent_case_contents = true csharp_indent_case_contents_when_block = true csharp_indent_labels = one_less_than_current csharp_indent_switch_labels = true # Space preferences csharp_space_after_cast = false csharp_space_after_colon_in_inheritance_clause = true csharp_space_after_comma = true csharp_space_after_dot = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_after_semicolon_in_for_statement = true csharp_space_around_binary_operators = before_and_after csharp_space_around_declaration_statements = false csharp_space_before_colon_in_inheritance_clause = true csharp_space_before_comma = false csharp_space_before_dot = false csharp_space_before_open_square_brackets = false csharp_space_before_semicolon_in_for_statement = false csharp_space_between_empty_square_brackets = false csharp_space_between_method_call_empty_parameter_list_parentheses = false csharp_space_between_method_call_name_and_opening_parenthesis = false csharp_space_between_method_call_parameter_list_parentheses = false csharp_space_between_method_declaration_empty_parameter_list_parentheses = false csharp_space_between_method_declaration_name_and_open_parenthesis = false csharp_space_between_method_declaration_parameter_list_parentheses = false csharp_space_between_parentheses = false csharp_space_between_square_brackets = false # Wrapping preferences csharp_preserve_single_line_blocks = true csharp_preserve_single_line_statements = true #### Naming styles #### # Naming rules dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion dotnet_naming_rule.types_should_be_pascal_case.symbols = types dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case # Symbol specifications dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.non_field_members.required_modifiers = # Naming styles dotnet_naming_style.pascal_case.required_prefix = dotnet_naming_style.pascal_case.required_suffix = dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_naming_style.begins_with_i.required_prefix = I dotnet_naming_style.begins_with_i.required_suffix = dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case ================================================ FILE: .github/workflows/deploy.yml ================================================ name: Deploy to GitHub Releases on: workflow_dispatch: inputs: version: description: 'Version number for the release' required: true default: '' jobs: deploy-to-github-releases: runs-on: windows-latest steps: - name: Checkout Repository uses: actions/checkout@v4 - name: Install .NET uses: actions/setup-dotnet@v4 with: dotnet-version: 10.0.x - name: Publish Application run: dotnet publish MangaJaNaiConverterGui/MangaJaNaiConverterGui.csproj -c Release -o publish -r win-x64 - name: Create Velopack Release run: | dotnet tool install -g vpk --prerelease vpk download github --repoUrl https://github.com/the-database/MangaJaNaiConverterGui vpk pack -u MangaJaNaiConverterGui -v ${{ github.event.inputs.version }} -p publish -i ./MangaJaNaiConverterGui/assets/logo.ico -e MangaJaNaiConverterGui.exe vpk upload github --repoUrl https://github.com/the-database/MangaJaNaiConverterGui --releaseName "${{ github.event.inputs.version }}" --tag ${{ github.event.inputs.version }} --token ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # User-specific files *.rsuser *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Mono auto generated files mono_crash.* # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Ww][Ii][Nn]32/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ [Ll]ogs/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUnit *.VisualState.xml TestResult.xml nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # ASP.NET Scaffolding ScaffoldingReadMe.txt # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_h.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *_wpftmp.csproj *.log *.tlog *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Coverlet is a free, cross platform Code Coverage Tool coverage*.json coverage*.xml coverage*.info # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # NuGet Symbol Packages *.snupkg # The packages folder can be ignored because of Package Restore # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx *.appxbundle *.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !?*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser *- [Bb]ackup.rdl *- [Bb]ackup ([0-9]).rdl *- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio 6 auto-generated project file (contains which files were open etc.) *.vbp # Visual Studio 6 workspace and project file (working project files containing files to include in project) *.dsw *.dsp # Visual Studio 6 technical files *.ncb *.aps # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # CodeRush personal settings .cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ # Visual Studio History (VSHistory) files .vshistory/ # BeatPulse healthcheck temp database healthchecksdb # Backup folder for Package Reference Convert tool in Visual Studio 2017 MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ # Fody - auto-generated XML schema FodyWeavers.xsd # VS Code files for those working on multiple tools .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json *.code-workspace # Local History for Visual Studio Code .history/ # Windows Installer files from build outputs *.cab *.msi *.msix *.msm *.msp # JetBrains Rider *.sln.iml MangaJaNaiConverterGui/chaiNNer/python/ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: MangaJaNaiConverterGui/App.axaml ================================================ ================================================ FILE: MangaJaNaiConverterGui/App.axaml.cs ================================================ using Autofac; using Avalonia; using Avalonia.Markup.Xaml; using MangaJaNaiConverterGui.Services; using MangaJaNaiConverterGui.ViewModels; using MangaJaNaiConverterGui.Views; using ReactiveUI; using Splat; using Splat.Autofac; using System.IO; using ReactiveUI; using ReactiveUI.Avalonia; using Splat; using Splat.Autofac; namespace MangaJaNaiConverterGui { public partial class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); } public override void OnFrameworkInitializationCompleted() { // Create a new Autofac container builder. var builder = new ContainerBuilder(); builder.RegisterType().AsSelf(); builder.RegisterType().As().SingleInstance(); builder.RegisterType().As().SingleInstance(); builder.RegisterType().As().SingleInstance(); // etc. // Register the Adapter to Splat. // Creates and sets the Autofac resolver as the Locator. var autofacResolver = builder.UseAutofacDependencyResolver(); // Register the resolver in Autofac so it can be later resolved. builder.RegisterInstance(autofacResolver); // Initialize ReactiveUI components. autofacResolver.InitializeReactiveUI(); var container = builder.Build(); autofacResolver.SetLifetimeScope(container); //var vm = container.Resolve(); var umService = container.Resolve(); if (umService.IsInstalled) { if (!Directory.Exists(Program.InstalledAppStateFolder)) { Directory.CreateDirectory(Program.InstalledAppStateFolder); } if (!File.Exists(Program.InstalledAppStatePath)) { File.Copy(Program.InstalledAppStateFilename, Program.InstalledAppStatePath); } } var suspension = new AutoSuspendHelper(ApplicationLifetime); RxApp.SuspensionHost.CreateNewAppState = () => new MainWindowViewModel(); RxApp.SuspensionHost.SetupDefaultSuspendResume(container.Resolve().SuspensionDriver); suspension.OnFrameworkInitializationCompleted(); // Load the saved view model state. var state = RxApp.SuspensionHost.GetAppState(); foreach (var wf in state.Workflows) { wf.Vm = state; foreach (var chain in wf.Chains) { chain.Vm = state; } } state.CurrentWorkflow?.Validate(); new MainWindow { DataContext = state }.Show(); base.OnFrameworkInitializationCompleted(); } } } ================================================ FILE: MangaJaNaiConverterGui/Drivers/NewtonsoftJsonSuspensionDriver.cs ================================================ using Newtonsoft.Json; using ReactiveUI; using System; using System.IO; using System.Reactive; using System.Reactive.Linq; namespace MangaJaNaiConverterGui.Drivers { public class NewtonsoftJsonSuspensionDriver : ISuspensionDriver { private readonly string _file; public static readonly JsonSerializerSettings Settings = new() { TypeNameHandling = TypeNameHandling.All, Formatting = Formatting.Indented, }; public NewtonsoftJsonSuspensionDriver(string file) => _file = file; public IObservable InvalidateState() { if (File.Exists(_file)) File.Delete(_file); return Observable.Return(Unit.Default); } public IObservable LoadState() { var lines = File.ReadAllText(_file); var state = JsonConvert.DeserializeObject(lines, Settings)!; return Observable.Return(state); } public IObservable SaveState(object state) { var lines = JsonConvert.SerializeObject(state, Settings); File.WriteAllText(_file, lines); return Observable.Return(Unit.Default); } } } ================================================ FILE: MangaJaNaiConverterGui/MangaJaNaiConverterGui.csproj ================================================  WinExe net10.0 enable true app.manifest true 1.0.0 logo.png Assets\logo.ico true Always PreserveNewest ================================================ FILE: MangaJaNaiConverterGui/Program.cs ================================================ using Avalonia; using ReactiveUI.Avalonia; using System; using System.IO; using Velopack; namespace MangaJaNaiConverterGui { internal class Program { public static bool WasFirstRun { get; private set; } public static readonly string InstalledAppStateFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MangaJaNaiConverterGui" ); public static readonly string InstalledAppStateFilename = "appstate2.json"; public static readonly string InstalledAppStatePath = Path.Combine(InstalledAppStateFolder, InstalledAppStateFilename); // Initialization code. Don't use any Avalonia, third-party APIs or any // SynchronizationContext-reliant code before AppMain is called: things aren't initialized // yet and stuff might break. [STAThread] public static void Main(string[] args) { VelopackApp.Build() .OnBeforeUninstallFastCallback((v) => { // On uninstall, remove Python and models from app data var pythonDir = Path.Combine(InstalledAppStateFolder, "python"); var modelsDir = Path.Combine(InstalledAppStateFolder, "models"); if (Directory.Exists(pythonDir)) { Directory.Delete(pythonDir, true); } if (Directory.Exists(modelsDir)) { Directory.Delete(modelsDir, true); } }) .OnFirstRun(_ => { WasFirstRun = true; }) .Run(); BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } // Avalonia configuration, don't remove; also used by visual designer. public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() .WithInterFont() .LogToTrace() .UseReactiveUI(); } } ================================================ FILE: MangaJaNaiConverterGui/Services/Downloader.cs ================================================ using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace MangaJaNaiConverterGui.Services { public class Downloader { public delegate void ProgressChanged(double percentage); public static async Task DownloadFileAsync(string url, string destinationFilePath, ProgressChanged progressChanged) { using HttpClient client = new(); using HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); long totalBytes = response.Content.Headers.ContentLength ?? -1L; using Stream contentStream = await response.Content.ReadAsStreamAsync(), fileStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true); var totalRead = 0L; var buffer = new byte[8192]; int read; while ((read = await contentStream.ReadAsync(buffer)) > 0) { await fileStream.WriteAsync(buffer.AsMemory(0, read)); totalRead += read; if (totalBytes != -1) { double percentage = Math.Round((double)totalRead / totalBytes * 100, 0); progressChanged?.Invoke(percentage); } } } } } ================================================ FILE: MangaJaNaiConverterGui/Services/ETACalculator.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using ProgressItem = System.Collections.Generic.KeyValuePair; namespace MangaJaNaiConverterGui.Services { public interface IETACalculator { /// Clears all collected data. /// void Reset(); /// Updates the current progress. /// /// The current level of completion. /// Must be between 0.0 and 1.0 (inclusively). void Update(float progress); /// Returns True when there is enough data to calculate the ETA. /// Returns False if the ETA is still calculating. /// bool ETAIsAvailable { get; } /// Calculates the Estimated Time of Arrival (Completion) /// DateTime ETA { get; } /// Calculates the Estimated Time Remaining. /// TimeSpan ETR { get; } } /// Calculates the "Estimated Time of Arrival" /// (or more accurately, "Estimated Time of Completion"), /// based on a "rolling average" of progress over time. /// public class ETACalculator : IETACalculator { /// /// /// /// The minimum number of data points required before ETA can be calculated. /// /// /// Determines how many seconds of data will be used to calculate the ETA. /// public ETACalculator(int minimumData, double maximumDuration) { this.minimumData = minimumData; maximumTicks = (long)(maximumDuration * Stopwatch.Frequency); queue = new Queue(minimumData * 2); timer = Stopwatch.StartNew(); } private int minimumData; private long maximumTicks; private readonly Stopwatch timer; private readonly Queue queue; private ProgressItem current; private ProgressItem oldest; public void Reset() { queue.Clear(); timer.Reset(); timer.Start(); } private void ClearExpired() { var expired = timer.ElapsedTicks - maximumTicks; while (queue.Count > minimumData && queue.Peek().Key < expired) { oldest = queue.Dequeue(); } } /// Adds the current progress to the calculation of ETA. /// /// The current level of completion. /// Must be between 0.0 and 1.0 (inclusively). public void Update(float progress) { // If progress hasn't changed, ignore: if (current.Value == progress) { return; } // Clear space for this item: ClearExpired(); // Queue this item: long currentTicks = timer.ElapsedTicks; current = new ProgressItem(currentTicks, progress); queue.Enqueue(current); // See if its the first item: if (queue.Count == 1) { oldest = current; } } /// Calculates the Estimated Time Remaining /// public TimeSpan ETR { get { // Create local copies of the oldest & current, // so that another thread can update them without locking: var oldest = this.oldest; var current = this.current; // Make sure we have enough items: if (queue.Count < minimumData || oldest.Value == current.Value) { return TimeSpan.MaxValue; } // Calculate the estimated finished time: double finishedInTicks = (1.0d - current.Value) * (current.Key - oldest.Key) / (current.Value - oldest.Value); return TimeSpan.FromSeconds(finishedInTicks / Stopwatch.Frequency); } } /// Calculates the Estimated Time of Arrival (Completion) /// public DateTime ETA { get { return DateTime.Now.Add(ETR); } } /// Returns True when there is enough data to calculate the ETA. /// Returns False if the ETA is still calculating. /// public bool ETAIsAvailable { get { // Make sure we have enough items: return queue.Count >= minimumData && oldest.Value != current.Value; } } } } ================================================ FILE: MangaJaNaiConverterGui/Services/IPythonService.cs ================================================ using Avalonia.Collections; using System; using System.Threading.Tasks; namespace MangaJaNaiConverterGui.Services { public interface IPythonService { bool IsPythonInstalled(); Task IsPythonUpdated(); Task IsBackendUpdated(); bool AreModelsInstalled(); string BackendUrl { get; } string BackendDirectory { get; } string LogsDirectory { get; } string PythonDirectory { get; } string ModelsDirectory { get; } string PythonPath { get; } string AppStateFolder { get; } string AppStatePath { get; } string AppStateFilename { get; } string InstallUpdatePythonDependenciesCommand { get; } string PythonBackendVersionPath { get; } Version BackendVersion { get; } void ExtractTgz(string gzArchiveName, string destFolder); void ExtractZip(string archivePath, string outFolder, ProgressChanged progressChanged); void Extract7z(string archivePath, string outFolder); void AddPythonPth(string destFolder); AvaloniaList AllModels { get; } } } ================================================ FILE: MangaJaNaiConverterGui/Services/ISuspensionDriverService.cs ================================================ using ReactiveUI; namespace MangaJaNaiConverterGui.Services { public interface ISuspensionDriverService { ISuspensionDriver SuspensionDriver { get; } } } ================================================ FILE: MangaJaNaiConverterGui/Services/IUpdateManagerService.cs ================================================ using System; using System.Threading.Tasks; using Velopack; namespace MangaJaNaiConverterGui.Services { public interface IUpdateManagerService { bool IsInstalled { get; } bool IsPortable { get; } string AppVersion { get; } bool IsUpdatePendingRestart { get; } void ApplyUpdatesAndRestart(UpdateInfo update); Task CheckForUpdatesAsync(); Task DownloadUpdatesAsync(UpdateInfo update, Action? progress = null); } } ================================================ FILE: MangaJaNaiConverterGui/Services/PythonService.cs ================================================ using Avalonia.Collections; using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using ICSharpCode.SharpZipLib.Zip; using SevenZipExtractor; using Splat; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MangaJaNaiConverterGui.Services { public delegate void ProgressChanged(double percentage); // https://github.com/chaiNNer-org/chaiNNer/blob/main/src/main/python/integratedPython.ts public class PythonService : IPythonService { private readonly IUpdateManagerService _updateManagerService; public static readonly Dictionary PYTHON_DOWNLOADS = new() { { "win32", new PythonDownload { Url = "https://github.com/astral-sh/python-build-standalone/releases/download/20251120/cpython-3.13.9+20251120-x86_64-pc-windows-msvc-install_only.tar.gz", Path = "python/python.exe", Version = "3.13.9", Filename = "Python.tar.gz" } }, }; public Version BackendVersion => new Version(1, 5, 0); public string BackendUrl => $"https://github.com/the-database/MangaJaNaiConverterGui-backend/releases/download/{BackendVersion}/mangajanaiconvertergui-backend-{BackendVersion}.7z"; public PythonService(IUpdateManagerService? updateManagerService = null) { _updateManagerService = updateManagerService ?? Locator.Current.GetService()!; } public string BackendDirectory => (_updateManagerService?.IsInstalled ?? false) ? Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"MangaJaNaiConverterGui") : Path.GetFullPath(@".\backend"); public string LogsDirectory => Path.Combine(BackendDirectory, "logs"); public string ModelsDirectory => Path.Combine(BackendDirectory, "models"); public string PythonDirectory => Path.Combine(BackendDirectory, "python"); public string PythonBackendVersionPath => Path.Combine(PythonDirectory, "Version.txt"); public string PythonPath => Path.GetFullPath(Path.Join(PythonDirectory, PYTHON_DOWNLOADS["win32"].Path)); public string AppStateFolder => ((_updateManagerService?.IsInstalled ?? false) && !(_updateManagerService?.IsPortable ?? false)) ? Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"MangaJaNaiConverterGui") : Path.GetFullPath(@"."); public string AppStateFilename => "appstate2.json"; public string AppStatePath => Path.Join(AppStateFolder, AppStateFilename); public bool IsPythonInstalled() => File.Exists(PythonPath); public async Task IsPythonUpdated() { var relPythonPath = @".\python\python\python.exe"; var cmd = $@"{relPythonPath} -V"; // Create a new process to run the CMD command using (var process = new Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = @$"/C {cmd}"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; process.StartInfo.WorkingDirectory = BackendDirectory; Version? result = null; // Create a StreamWriter to write the output to a log file try { process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { // ignore } }; process.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { result = new Version(e.Data.Replace("Python ", "")); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Start asynchronous reading of the output await process.WaitForExitAsync(); } catch (IOException) { } if (result == null || result.CompareTo(new Version(PYTHON_DOWNLOADS["win32"].Version)) < 0) { return false; } } return true; } public async Task IsBackendUpdated() { if (File.Exists(PythonBackendVersionPath)) { var currentVersion = new Version(await File.ReadAllTextAsync(PythonBackendVersionPath)); return currentVersion.CompareTo(BackendVersion) >= 0; } return false; } public bool AreModelsInstalled() => Directory.Exists(ModelsDirectory) && Directory.GetFiles(ModelsDirectory).Length > 0 && Directory.GetFiles(ModelsDirectory).Any(x => x.Contains("2x_IllustrationJaNai_V3denoise_FDAT_M_unshuffle_30k_fp16")); public class PythonDownload { public string Url { get; set; } public string Version { get; set; } public string Path { get; set; } public string Filename { get; set; } } public void ExtractTgz(string gzArchiveName, string destFolder) { Stream inStream = File.OpenRead(gzArchiveName); Stream gzipStream = new GZipInputStream(inStream); TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream, Encoding.UTF8); tarArchive.ExtractContents(destFolder); tarArchive.Close(); gzipStream.Close(); inStream.Close(); } public void ExtractZip(string archivePath, string outFolder, ProgressChanged progressChanged) { using (var fsInput = File.OpenRead(archivePath)) using (var zf = new ZipFile(fsInput)) { for (var i = 0; i < zf.Count; i++) { ZipEntry zipEntry = zf[i]; if (!zipEntry.IsFile) { // Ignore directories continue; } String entryFileName = zipEntry.Name; // to remove the folder from the entry: //entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here // to skip as desired. // The unpacked length is available in the zipEntry.Size property. // Manipulate the output filename here as desired. var fullZipToPath = Path.Combine(outFolder, entryFileName); var directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } // 4K is optimum var buffer = new byte[4096]; // Unzip file in buffered chunks. This is just as fast as unpacking // to a buffer the full size of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (var zipStream = zf.GetInputStream(zipEntry)) using (Stream fsOutput = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, fsOutput, buffer); } var percentage = Math.Round((double)i / zf.Count * 100, 0); progressChanged?.Invoke(percentage); } } } public void Extract7z(string archiveName, string outFolder) { using ArchiveFile archiveFile = new(archiveName); archiveFile.Extract(outFolder); } public void AddPythonPth(string destFolder) { string[] lines = { "python313.zip", "DLLs", "Lib", ".", "Lib/site-packages" }; var filename = "python313._pth"; using var outputFile = new StreamWriter(Path.Combine(destFolder, filename)); foreach (string line in lines) outputFile.WriteLine(line); } public string InstallUpdatePythonDependenciesCommand { get { var relPythonPath = @".\python\python\python.exe"; return $@"{relPythonPath} -m pip install -U pip wheel --no-warn-script-location && {relPythonPath} -m pip install torch==2.9.1 torchvision --index-url https://download.pytorch.org/whl/cu128 --no-warn-script-location && {relPythonPath} -m pip install ""{Path.GetFullPath(@".\backend\src")}"" --no-warn-script-location"; } } private AvaloniaList? _allModels; public AvaloniaList AllModels { get { if (_allModels == null) { try { var models = new AvaloniaList(Directory.GetFiles(ModelsDirectory).Where(filename => Path.GetExtension(filename).Equals(".pth", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filename).Equals(".pt", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filename).Equals(".ckpt", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filename).Equals(".safetensors", StringComparison.CurrentCultureIgnoreCase) ) .Select(filename => Path.GetFileName(filename)) .Order().ToList()); models.Add("No Model"); Debug.WriteLine($"GetAllModels: {models.Count}"); _allModels = models; } catch (DirectoryNotFoundException) { Debug.WriteLine($"GetAllModels: DirectoryNotFoundException"); return []; } } return _allModels; } } } } ================================================ FILE: MangaJaNaiConverterGui/Services/SuspensionDriverService.cs ================================================ using MangaJaNaiConverterGui.Drivers; using ReactiveUI; namespace MangaJaNaiConverterGui.Services { public class SuspensionDriverService(IPythonService pythonService) : ISuspensionDriverService { private readonly ISuspensionDriver _driver = new NewtonsoftJsonSuspensionDriver(pythonService.AppStatePath); public ISuspensionDriver SuspensionDriver => _driver; } } ================================================ FILE: MangaJaNaiConverterGui/Services/UpdateManagerService.cs ================================================ using System; using System.Threading.Tasks; using Velopack; using Velopack.Sources; namespace MangaJaNaiConverterGui.Services { public class UpdateManagerService : IUpdateManagerService { private readonly UpdateManager _um; public UpdateManagerService() { _um = new UpdateManager(new GithubSource("https://github.com/the-database/MangaJaNaiConverterGui", null, false)); } public string AppVersion { get => _um?.CurrentVersion?.ToString() ?? ""; } public bool IsInstalled { get => _um.IsInstalled; } public bool IsPortable { get => _um.IsPortable; } public bool IsUpdatePendingRestart { get => _um.IsUpdatePendingRestart; } public void ApplyUpdatesAndRestart(UpdateInfo update) { _um.ApplyUpdatesAndRestart(update); } public async Task CheckForUpdatesAsync() { return await _um.CheckForUpdatesAsync(); } public Task DownloadUpdatesAsync(UpdateInfo update, Action? progress = null) { return _um.DownloadUpdatesAsync(update, progress); } } } ================================================ FILE: MangaJaNaiConverterGui/ViewLocator.cs ================================================ using Avalonia.Controls; using Avalonia.Controls.Templates; using MangaJaNaiConverterGui.ViewModels; using System; namespace MangaJaNaiConverterGui { public class ViewLocator : IDataTemplate { public Control Build(object data) { var name = data.GetType().FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { return (Control)Activator.CreateInstance(type)!; } return new TextBlock { Text = "Not Found: " + name }; } public bool Match(object data) { return data is ViewModelBase; } } } ================================================ FILE: MangaJaNaiConverterGui/ViewModels/MainWindowViewModel.cs ================================================ using Avalonia.Collections; using Avalonia.Threading; using MangaJaNaiConverterGui.Drivers; using MangaJaNaiConverterGui.Services; using Newtonsoft.Json; using ReactiveUI; using Splat; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Reactive.Linq; using System.Runtime.Serialization; using System.Text; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using Velopack; using File = System.IO.File; using Path = System.IO.Path; namespace MangaJaNaiConverterGui.ViewModels { [DataContract] public class MainWindowViewModel : ViewModelBase { public static readonly List IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".bmp", ".avif"]; public static readonly List ARCHIVE_EXTENSIONS = [".zip", ".cbz", ".rar", ".cbr"]; private readonly DispatcherTimer _timer = new(); private static readonly HttpClient client = new(); private UpdateInfo? _update = null; private readonly IPythonService _pythonService; private readonly IUpdateManagerService _updateManagerService; private readonly ISuspensionDriverService _suspensionDriverService; public MainWindowViewModel(IPythonService? pythonService = null, IUpdateManagerService? updateManagerService = null, ISuspensionDriverService? suspensionDriverService = null) { _pythonService = pythonService ?? Locator.Current.GetService()!; _updateManagerService = updateManagerService ?? Locator.Current.GetService()!; _suspensionDriverService = suspensionDriverService ?? Locator.Current.GetService()!; var g1 = this.WhenAnyValue ( x => x.SelectedWorkflowIndex ).Subscribe(x => { CurrentWorkflow?.Validate(); }); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += _timer_Tick; ShowDialog = new Interaction(); CheckAndDoBackup(); CheckForUpdates(); } private string[] _commonResolutions = [ "0x0", "0x1250", "0x1251", "0x1350", "0x1351", "0x1450", "0x1451", "0x1550", "0x1551", "0x1760", "0x1761", "0x1984", "0x1985",]; private static readonly string DEFAULT_WORKFLOW = """ { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleWorkflow, MangaJaNaiConverterGui", "WorkflowName": "Upscale Manga (Default)", "WorkflowIndex": 0, "SelectedTabIndex": 0, "InputFilePath": "", "InputFolderPath": "", "OutputFilename": "%filename%-mangajanai", "OutputFolderPath": "", "OverwriteExistingFiles": false, "UpscaleImages": true, "UpscaleArchives": true, "ResizeHeightAfterUpscale": 2160, "ResizeWidthAfterUpscale": 3840, "WebpSelected": true, "AvifSelected": false, "PngSelected": false, "JpegSelected": false, "UseLosslessCompression": false, "LossyCompressionQuality": 80, "ShowLossySettings": true, "ModeScaleSelected": true, "UpscaleScaleFactor": 4, "ModeWidthSelected": false, "ModeHeightSelected": false, "ModeFitToDisplaySelected": false, "DisplayDevice": "Kobo Elipsa 2E (2023)", "DisplayDeviceWidth": 1404, "DisplayDeviceHeight": 1872, "DisplayPortraitSelected": true, "ShowAdvancedSettings": false, "GrayscaleDetectionThreshold": 12, "Chains": { "$type": "Avalonia.Collections.AvaloniaList`1[[MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui]], Avalonia.Base", "$values": [ { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "1", "MinResolution": "0x0", "MaxResolution": "0x0", "IsGrayscale": false, "IsColor": true, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_IllustrationJaNai_V3denoise_FDAT_M_unshuffle_30k_fp16.safetensors", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": false, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "2", "MinResolution": "0x0", "MaxResolution": "0x0", "IsGrayscale": false, "IsColor": true, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_IllustrationJaNai_V3denoise_FDAT_M_47k_fp16.safetensors", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": false, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "3", "MinResolution": "0x0", "MaxResolution": "0x1250", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_1200p_V1_ESRGAN_70k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "4", "MinResolution": "0x0", "MaxResolution": "0x1250", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_1200p_V1_ESRGAN_70k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "5", "MinResolution": "0x1251", "MaxResolution": "0x1350", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_1300p_V1_ESRGAN_75k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "6", "MinResolution": "0x1251", "MaxResolution": "0x1350", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_1300p_V1_ESRGAN_75k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "7", "MinResolution": "0x1351", "MaxResolution": "0x1450", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_1400p_V1_ESRGAN_70k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "8", "MinResolution": "0x1351", "MaxResolution": "0x1450", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_1400p_V1_ESRGAN_105k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "9", "MinResolution": "0x1451", "MaxResolution": "0x1550", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_1500p_V1_ESRGAN_90k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "10", "MinResolution": "0x1451", "MaxResolution": "0x1550", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_1500p_V1_ESRGAN_105k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "11", "MinResolution": "0x1551", "MaxResolution": "0x1760", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_1600p_V1_ESRGAN_90k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "12", "MinResolution": "0x1551", "MaxResolution": "0x1760", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_1600p_V1_ESRGAN_70k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "13", "MinResolution": "0x1761", "MaxResolution": "0x1984", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_1920p_V1_ESRGAN_70k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "14", "MinResolution": "0x1761", "MaxResolution": "0x1984", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_1920p_V1_ESRGAN_105k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "15", "MinResolution": "0x1985", "MaxResolution": "0x0", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 0, "MaxScaleFactor": 2, "ModelFilePath": "2x_MangaJaNai_2048p_V1_ESRGAN_95k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 }, { "$type": "MangaJaNaiConverterGui.ViewModels.UpscaleChain, MangaJaNaiConverterGui", "ChainNumber": "16", "MinResolution": "0x1985", "MaxResolution": "0x0", "IsGrayscale": true, "IsColor": false, "MinScaleFactor": 2, "MaxScaleFactor": 0, "ModelFilePath": "4x_MangaJaNai_2048p_V1_ESRGAN_70k.pth", "ModelTileSize": "Auto (Estimate)", "AutoAdjustLevels": true, "ResizeHeightBeforeUpscale": 0, "ResizeWidthBeforeUpscale": 0, "ResizeFactorBeforeUpscale": 100.0 } ] } } """; public string[] CommonResolutions { get => _commonResolutions; set => this.RaiseAndSetIfChanged(ref _commonResolutions, value); } public Interaction ShowDialog { get; } private void _timer_Tick(object? sender, EventArgs e) { ElapsedTime = ElapsedTime.Add(TimeSpan.FromSeconds(1)); } private CancellationTokenSource? _cancellationTokenSource; private Process? _runningProcess = null; private readonly IETACalculator _archiveEtaCalculator = new ETACalculator(2, 3.0); private readonly IETACalculator _totalEtaCalculator = new ETACalculator(2, 3.0); public TimeSpan ArchiveEtr => _archiveEtaCalculator.ETAIsAvailable ? _archiveEtaCalculator.ETR : TimeSpan.FromSeconds(0); public string ArchiveEta => _archiveEtaCalculator.ETAIsAvailable ? _archiveEtaCalculator.ETA.ToString("t") : "please wait"; public TimeSpan TotalEtr => _totalEtaCalculator.ETAIsAvailable ? _totalEtaCalculator.ETR : ArchiveEtr + (ElapsedTime + ArchiveEtr) * (ProgressTotalFiles - (ProgressCurrentFile + 1)); public string TotalEta => _totalEtaCalculator.ETAIsAvailable ? _totalEtaCalculator.ETA.ToString("t") : _archiveEtaCalculator.ETAIsAvailable ? DateTime.Now.Add(TotalEtr).ToString("t") : "please wait"; public bool IsInstalled => _updateManagerService.IsInstalled; [DataMember] public string ModelsDirectory => _pythonService.ModelsDirectory; private bool _showCheckUpdateButton = true; public bool ShowCheckUpdateButton { get => _showCheckUpdateButton; set => this.RaiseAndSetIfChanged(ref _showCheckUpdateButton, value); } private bool _showDownloadButton = false; public bool ShowDownloadButton { get => _showDownloadButton; set { this.RaiseAndSetIfChanged(ref _showDownloadButton, value); this.RaisePropertyChanged(nameof(ShowCheckUpdateButton)); } } private bool _showApplyButton = false; public bool ShowApplyButton { get => _showApplyButton; set { this.RaiseAndSetIfChanged(ref _showApplyButton, value); this.RaisePropertyChanged(nameof(ShowCheckUpdateButton)); } } public string AppVersion => _updateManagerService.AppVersion; private string _updateStatusText = string.Empty; public string UpdateStatusText { get => _updateStatusText; set => this.RaiseAndSetIfChanged(ref _updateStatusText, value); } private string[] _tileSizes = [ "Auto (Estimate)", "Maximum", "No Tiling", "128", "192", "256", "384", "512", "768", "1024", "2048", "4096"]; public string[] TileSizes { get => _tileSizes; set => this.RaiseAndSetIfChanged(ref _tileSizes, value); } private string[] _deviceList = []; public string[] DeviceList { get => _deviceList; set { this.RaiseAndSetIfChanged(ref _deviceList, value); this.RaisePropertyChanged(nameof(SelectedDeviceIndex)); } } private string _pythonPipList = string.Empty; public string PythonPipList { get => _pythonPipList; set => this.RaiseAndSetIfChanged(ref _pythonPipList, value); } private AvaloniaDictionary _displayDeviceMap = []; [DataMember] public AvaloniaDictionary DisplayDeviceMap { get => _displayDeviceMap; set => this.RaiseAndSetIfChanged(ref _displayDeviceMap, value); } private bool _autoUpdate; [DataMember] public bool AutoUpdateEnabled { get => _autoUpdate; set => this.RaiseAndSetIfChanged(ref _autoUpdate, value); } private int _selectedDeviceIndex; [DataMember] public int SelectedDeviceIndex { get => _selectedDeviceIndex; set => this.RaiseAndSetIfChanged(ref _selectedDeviceIndex, value); } private bool _useCpu; [DataMember] public bool UseCpu { get => _useCpu; set => this.RaiseAndSetIfChanged(ref _useCpu, value); } private bool _useFp16; [DataMember] public bool UseFp16 { get => _useFp16; set => this.RaiseAndSetIfChanged(ref _useFp16, value); } private bool _upscaling = false; [IgnoreDataMember] public bool Upscaling { get => _upscaling; set { this.RaiseAndSetIfChanged(ref _upscaling, value); this.RaisePropertyChanged(nameof(UpscaleEnabled)); this.RaisePropertyChanged(nameof(LeftStatus)); } } private string _validationText = string.Empty; public string ValidationText { get => _validationText; set { this.RaiseAndSetIfChanged(ref _validationText, value); this.RaisePropertyChanged(nameof(LeftStatus)); } } private string _backendSetupMainStatus = string.Empty; public string BackendSetupMainStatus { get => this._backendSetupMainStatus; set { this.RaiseAndSetIfChanged(ref _backendSetupMainStatus, value); } } public string BackendSetupSubStatusText => string.Join("\n", BackendSetupSubStatusQueue); private static readonly int BACKEND_SETUP_SUB_STATUS_QUEUE_CAPACITY = 50; private ConcurrentQueue _backendSetupSubStatusQueue = new(); public ConcurrentQueue BackendSetupSubStatusQueue { get => this._backendSetupSubStatusQueue; set { this.RaiseAndSetIfChanged(ref _backendSetupSubStatusQueue, value); this.RaisePropertyChanged(nameof(BackendSetupSubStatusText)); } } public string ConsoleText => string.Join("\n", ConsoleQueue); private static readonly int CONSOLE_QUEUE_CAPACITY = 1000; private ConcurrentQueue _consoleQueue = new(); public ConcurrentQueue ConsoleQueue { get => this._consoleQueue; set { this.RaiseAndSetIfChanged(ref _consoleQueue, value); this.RaisePropertyChanged(nameof(ConsoleText)); } } private bool _showConsole = false; public bool ShowConsole { get => _showConsole; set => this.RaiseAndSetIfChanged(ref _showConsole, value); } private bool _showAppSettings = false; public bool RequestShowAppSettings { get => _showAppSettings; set { this.RaiseAndSetIfChanged(ref _showAppSettings, value); this.RaisePropertyChanged(nameof(ShowAppSettings)); this.RaisePropertyChanged(nameof(ShowMainForm)); } } public string PythonPath => _pythonService.PythonPath; private bool _isExtractingBackend = true; public bool IsExtractingBackend { get => _isExtractingBackend; set { this.RaiseAndSetIfChanged(ref _isExtractingBackend, value); this.RaisePropertyChanged(nameof(RequestShowAppSettings)); this.RaisePropertyChanged(nameof(ShowMainForm)); } } public bool ShowAppSettings => RequestShowAppSettings && !IsExtractingBackend; public bool ShowMainForm => !RequestShowAppSettings && !IsExtractingBackend; private bool _showEstimates = false; public bool ShowEstimates { get => _showEstimates; set => this.RaiseAndSetIfChanged(ref _showEstimates, value); } private string _inputStatusText = string.Empty; public string InputStatusText { get => _inputStatusText; set { this.RaiseAndSetIfChanged(ref _inputStatusText, value); this.RaisePropertyChanged(nameof(LeftStatus)); } } public string LeftStatus => !CurrentWorkflow.Valid ? ValidationText.Replace("\n", " ") : $"{InputStatusText} selected for upscaling."; private int _progressCurrentFile = 0; public int ProgressCurrentFile { get => _progressCurrentFile; set => this.RaiseAndSetIfChanged(ref _progressCurrentFile, value); } private int _progressTotalFiles = 0; public int ProgressTotalFiles { get => _progressTotalFiles; set => this.RaiseAndSetIfChanged(ref _progressTotalFiles, value); } private int _progressCurrentFileInCurrentArchive = 0; public int ProgressCurrentFileInArchive { get => _progressCurrentFileInCurrentArchive; set => this.RaiseAndSetIfChanged(ref _progressCurrentFileInCurrentArchive, value); } private int _progressTotalFilesInCurrentArchive = 0; public int ProgressTotalFilesInCurrentArchive { get => _progressTotalFilesInCurrentArchive; set => this.RaiseAndSetIfChanged(ref _progressTotalFilesInCurrentArchive, value); } private bool _showArchiveProgressBar = false; public bool ShowArchiveProgressBar { get => _showArchiveProgressBar; set => this.RaiseAndSetIfChanged(ref _showArchiveProgressBar, value); } public bool UpscaleEnabled => CurrentWorkflow.Valid && !Upscaling; private TimeSpan _elapsedTime = TimeSpan.FromSeconds(0); public TimeSpan ElapsedTime { get => _elapsedTime; set { this.RaiseAndSetIfChanged(ref _elapsedTime, value); } } private AvaloniaList? _workflows; [DataMember] public AvaloniaList? Workflows { get => _workflows; set => this.RaiseAndSetIfChanged(ref _workflows, value); } public AvaloniaList CustomWorkflows => new(Workflows.Skip(1).ToList()); private int _selectedWorkflowIndex = 0; [DataMember] public int SelectedWorkflowIndex { get => _selectedWorkflowIndex; set { this.RaiseAndSetIfChanged(ref _selectedWorkflowIndex, value); this.RaisePropertyChanged(nameof(CurrentWorkflow)); this.RaisePropertyChanged(nameof(CurrentWorkflow.ActiveWorkflow)); } } public UpscaleWorkflow? CurrentWorkflow { get => Workflows?[SelectedWorkflowIndex]; set { if (Workflows != null) { Workflows[SelectedWorkflowIndex] = value; this.RaisePropertyChanged(nameof(CurrentWorkflow)); this.RaisePropertyChanged(nameof(CustomWorkflows)); } } } public void HandleWorkflowSelected(int workflowIndex) { SelectedWorkflowIndex = workflowIndex; RequestShowAppSettings = false; } public void HandleAppSettingsSelected() { RequestShowAppSettings = true; } public async Task RunUpscale() { _cancellationTokenSource = new CancellationTokenSource(); var ct = _cancellationTokenSource.Token; var task = Task.Run(async () => { await _suspensionDriverService.SuspensionDriver.SaveState(this); ElapsedTime = TimeSpan.FromSeconds(0); ShowEstimates = true; _archiveEtaCalculator.Reset(); _totalEtaCalculator.Reset(); ct.ThrowIfCancellationRequested(); ConsoleQueueClear(); Upscaling = true; ProgressCurrentFile = 0; ProgressCurrentFileInArchive = 0; ShowArchiveProgressBar = false; var cmd = $@".\python\python\python.exe ""{Path.GetFullPath(@".\backend\src\run_upscale.py")}"" --settings ""{_pythonService.AppStatePath}"""; ConsoleQueueEnqueue($"Upscaling with command: {cmd}"); await RunCommand($@" /C {cmd}"); CurrentWorkflow.Valid = true; }, ct); try { _timer.Start(); await task; _timer.Stop(); CurrentWorkflow.Validate(); } catch (OperationCanceledException e) { _timer.Stop(); Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {e.Message}"); Upscaling = false; } finally { _timer.Stop(); _cancellationTokenSource.Dispose(); Upscaling = false; } } public void CancelUpscale() { try { _cancellationTokenSource?.Cancel(); if (_runningProcess != null && !_runningProcess.HasExited) { // Kill the process _runningProcess.Kill(true); _runningProcess = null; // Clear the reference to the terminated process } CurrentWorkflow.Validate(); } catch { } } public void CheckInputs() { if (CurrentWorkflow.Valid && !Upscaling) { var overwriteText = CurrentWorkflow.OverwriteExistingFiles ? "overwritten" : "skipped"; // input file if (CurrentWorkflow.SelectedTabIndex == 0) { StringBuilder status = new(); var skipFiles = 0; if (IMAGE_EXTENSIONS.Any(x => CurrentWorkflow.InputFilePath.ToLower().EndsWith(x))) { var outputFilePath = Path.Join( Path.GetFullPath(CurrentWorkflow.OutputFolderPath), CurrentWorkflow.OutputFilename.Replace("%filename%", Path.GetFileNameWithoutExtension(CurrentWorkflow.InputFilePath))) + $".{CurrentWorkflow.ImageFormat}"; if (File.Exists(outputFilePath)) { status.Append($" (1 image already exists and will be {overwriteText})"); if (!CurrentWorkflow.OverwriteExistingFiles) { skipFiles++; } } } else if (ARCHIVE_EXTENSIONS.Any(x => CurrentWorkflow.InputFilePath.ToLower().EndsWith(x))) { var outputFilePath = Path.Join(Path.GetFullPath(CurrentWorkflow.OutputFolderPath), CurrentWorkflow.OutputFilename.Replace("%filename%", Path.GetFileNameWithoutExtension(CurrentWorkflow.InputFilePath))) + ".cbz"; if (File.Exists(outputFilePath)) { status.Append($" (1 archive already exists and will be {overwriteText})"); if (!CurrentWorkflow.OverwriteExistingFiles) { skipFiles++; } } } else { // TODO ??? } var s = skipFiles > 0 ? "s" : ""; if (IMAGE_EXTENSIONS.Any(x => CurrentWorkflow.InputFilePath.ToLower().EndsWith(x))) { status.Insert(0, $"{1 - skipFiles} image{s}"); } else if (ARCHIVE_EXTENSIONS.Any(x => CurrentWorkflow.InputFilePath.ToLower().EndsWith(x))) { status.Insert(0, $"{1 - skipFiles} archive{s}"); } else { status.Insert(0, "0 files"); } InputStatusText = status.ToString(); ProgressCurrentFile = 0; ProgressTotalFiles = 1 - skipFiles; ProgressCurrentFileInArchive = 0; ProgressTotalFilesInCurrentArchive = 0; ShowArchiveProgressBar = false; } else // input folder { List statuses = new(); var existImageCount = 0; var existArchiveCount = 0; var totalFileCount = 0; if (CurrentWorkflow.UpscaleImages) { var images = Directory.EnumerateFiles(CurrentWorkflow.InputFolderPath, "*.*", SearchOption.AllDirectories) .Where(file => IMAGE_EXTENSIONS.Any(ext => file.ToLower().EndsWith(ext))); var imagesCount = 0; foreach (var inputImagePath in images) { var outputImagePath = Path.Join( Path.GetFullPath(CurrentWorkflow.OutputFolderPath), CurrentWorkflow.OutputFilename.Replace("%filename%", Path.GetFileNameWithoutExtension(inputImagePath))) + $"{CurrentWorkflow.ImageFormat}"; // if out file exists, exist count ++ // if overwrite image OR out file doesn't exist, count image++ var fileExists = File.Exists(outputImagePath); if (fileExists) { existImageCount++; } if (!fileExists || CurrentWorkflow.OverwriteExistingFiles) { imagesCount++; } } var imageS = imagesCount == 1 ? "" : "s"; var existImageS = existImageCount == 1 ? "" : "s"; statuses.Add($"{imagesCount} image{imageS} ({existImageCount} image{existImageS} already exist and will be {overwriteText})"); totalFileCount += imagesCount; } if (CurrentWorkflow.UpscaleArchives) { var archives = Directory.EnumerateFiles(CurrentWorkflow.InputFolderPath, "*.*", SearchOption.AllDirectories) .Where(file => ARCHIVE_EXTENSIONS.Any(ext => file.ToLower().EndsWith(ext))); var archivesCount = 0; foreach (var inputArchivePath in archives) { var outputArchivePath = Path.Join( Path.GetFullPath(CurrentWorkflow.OutputFolderPath), CurrentWorkflow.OutputFilename.Replace("%filename%", Path.GetFileNameWithoutExtension(inputArchivePath))) + ".cbz"; var fileExists = File.Exists(outputArchivePath); if (fileExists) { existArchiveCount++; } if (!fileExists || CurrentWorkflow.OverwriteExistingFiles) { archivesCount++; } } var archiveS = archivesCount == 1 ? "" : "s"; var existArchiveS = existArchiveCount == 1 ? "" : "s"; statuses.Add($"{archivesCount} archive{archiveS} ({existArchiveCount} archive{existArchiveS} already exist and will be {overwriteText})"); totalFileCount += archivesCount; } if (!CurrentWorkflow.UpscaleArchives && !CurrentWorkflow.UpscaleImages) { InputStatusText = "0 files"; } else { InputStatusText = $"{string.Join(" and ", statuses)}"; } ProgressCurrentFile = 0; ProgressTotalFiles = totalFileCount; ProgressCurrentFileInArchive = 0; ProgressTotalFilesInCurrentArchive = 0; ShowArchiveProgressBar = false; } } } public void AddChain() { CurrentWorkflow?.Chains.Add(new UpscaleChain { Vm = this, }); UpdateChainHeaders(); } public void DeleteChain(UpscaleChain chain) { try { CurrentWorkflow.Chains.Remove(chain); } catch (ArgumentOutOfRangeException) { } UpdateChainHeaders(); } public void UpdateChainHeaders() { for (var i = 0; i < CurrentWorkflow.Chains.Count; i++) { CurrentWorkflow.Chains[i].ChainNumber = (i + 1).ToString(); } } public async Task RunCommand(string command) { // Create a new process to run the CMD command using (var process = new Process()) { _runningProcess = process; process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = command; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = _pythonService.BackendDirectory; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; // Create a StreamWriter to write the output to a log file using (var outputFile = new StreamWriter(Path.Combine(_pythonService.LogsDirectory, "upscale.log"), append: false)) { process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { outputFile.WriteLine(e.Data); // Write the output to the log file ConsoleQueueEnqueue(e.Data); } }; process.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { if (e.Data.StartsWith("PROGRESS=")) { if (e.Data.Contains("_zip_image")) { ShowArchiveProgressBar = true; ProgressCurrentFileInArchive++; UpdateEtas(); } else { ProgressCurrentFile++; UpdateEtas(); } } else if (e.Data.StartsWith("TOTALZIP=")) { if (int.TryParse(e.Data.Replace("TOTALZIP=", ""), out var total)) { ShowArchiveProgressBar = true; ProgressCurrentFileInArchive = 0; ProgressTotalFilesInCurrentArchive = total; UpdateEtas(); } } else { outputFile.WriteLine(e.Data); // Write the output to the log file ConsoleQueueEnqueue(e.Data); Debug.WriteLine(e.Data); } } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Start asynchronous reading of the output await process.WaitForExitAsync(); } } } public async Task InitializeDeviceList() { if (!File.Exists(@".\backend\src\device_list.py")) { return null; } // Create a new process to run the CMD command using (var process = new Process()) { _runningProcess = process; process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = @$"/C .\python\python\python.exe {Path.GetFullPath(@".\backend\src\device_list.py")}"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = _pythonService.BackendDirectory; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; var result = string.Empty; // Create a StreamWriter to write the output to a log file try { using var outputFile = new StreamWriter(Path.Combine(_pythonService.LogsDirectory, "upscale.log"), append: false); process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { //outputFile.WriteLine(e.Data); // Write the output to the log file //ConsoleQueueEnqueue(e.Data); Debug.WriteLine(e.Data); } }; process.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { result = e.Data; Debug.WriteLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Start asynchronous reading of the output await process.WaitForExitAsync(); if (!string.IsNullOrEmpty(result)) { return JsonConvert.DeserializeObject(result); } } catch (IOException) { } } return null; } public async Task RunPythonPipList() { List result = []; // Create a new process to run the CMD command using (var process = new Process()) { _runningProcess = process; process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = @$"/C .\python\python\python.exe -m pip list"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = _pythonService.BackendDirectory; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; // Create a StreamWriter to write the output to a log file try { process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { //outputFile.WriteLine(e.Data); // Write the output to the log file //ConsoleQueueEnqueue(e.Data); Debug.WriteLine(e.Data); } }; process.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { result.Add(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Start asynchronous reading of the output await process.WaitForExitAsync(); } catch (IOException) { } } return string.Join("\n", result); } public async void ShowSettingsDialog() { var result = await ShowDialog.Handle(this); } private void UpdateEtas() { if (ProgressTotalFilesInCurrentArchive > 0) { _archiveEtaCalculator.Update(ProgressCurrentFileInArchive / (float)ProgressTotalFilesInCurrentArchive); } if (ProgressTotalFiles > 0) { _totalEtaCalculator.Update(ProgressCurrentFile / (float)ProgressTotalFiles); } this.RaisePropertyChanged(nameof(ArchiveEtr)); this.RaisePropertyChanged(nameof(ArchiveEta)); this.RaisePropertyChanged(nameof(TotalEtr)); this.RaisePropertyChanged(nameof(TotalEta)); } private void ConsoleQueueClear() { ConsoleQueue.Clear(); this.RaisePropertyChanged(nameof(ConsoleText)); } private void ConsoleQueueEnqueue(string value) { while (ConsoleQueue.Count > CONSOLE_QUEUE_CAPACITY) { ConsoleQueue.TryDequeue(out var _); } ConsoleQueue.Enqueue(value); this.RaisePropertyChanged(nameof(ConsoleText)); } private void BackendSetupSubStatusQueueEnqueue(string value) { while (BackendSetupSubStatusQueue.Count > BACKEND_SETUP_SUB_STATUS_QUEUE_CAPACITY) { BackendSetupSubStatusQueue.TryDequeue(out var _); } BackendSetupSubStatusQueue.Enqueue(value); this.RaisePropertyChanged(nameof(BackendSetupSubStatusText)); } public void ReadWorkflowFileToCurrentWorkflow(string fullPath) { if (!File.Exists(fullPath)) { return; } var lines = File.ReadAllText(fullPath); var workflow = JsonConvert.DeserializeObject(lines, NewtonsoftJsonSuspensionDriver.Settings); if (workflow != null && CurrentWorkflow != null) { workflow.WorkflowIndex = CurrentWorkflow.WorkflowIndex; workflow.Vm = CurrentWorkflow.Vm; CurrentWorkflow = workflow; } } public void WriteCurrentWorkflowToFile(string fullPath) { var lines = JsonConvert.SerializeObject(CurrentWorkflow, NewtonsoftJsonSuspensionDriver.Settings); File.WriteAllText(fullPath, lines); } public async Task CheckAndExtractBackend() { await Task.Run(async () => { IsExtractingBackend = true; if (!Directory.Exists(_pythonService.LogsDirectory)) { Directory.CreateDirectory(_pythonService.LogsDirectory); } if (!_pythonService.AreModelsInstalled()) { await DownloadModels(); } if (!_pythonService.IsPythonInstalled() || !(await _pythonService.IsBackendUpdated())) { // Download Python tgz BackendSetupMainStatus = "Downloading Python Backend..."; var downloadUrl = _pythonService.BackendUrl; var targetPath = Path.Join(_pythonService.PythonDirectory, "backend.7z"); if (Directory.Exists(_pythonService.PythonDirectory)) { Directory.Delete(_pythonService.PythonDirectory, true); } Directory.CreateDirectory(_pythonService.PythonDirectory); await Downloader.DownloadFileAsync(downloadUrl, targetPath, (progress) => { BackendSetupMainStatus = $"Downloading Python Backend ({progress}%)..."; }); // Extract Python 7z BackendSetupMainStatus = "Extracting Python Backend..."; _pythonService.Extract7z(targetPath, _pythonService.PythonDirectory); Directory.Move(Path.Combine(_pythonService.PythonDirectory, "backend", "python"), Path.Combine(_pythonService.PythonDirectory, "python")); using (StreamWriter sw = File.CreateText(_pythonService.PythonBackendVersionPath)) { sw.WriteLine(_pythonService.BackendVersion); } Directory.Delete(Path.Combine(_pythonService.PythonDirectory, "backend")); File.Delete(targetPath); } IsExtractingBackend = false; }); var deviceResponse = await InitializeDeviceList(); if (deviceResponse != null) { DeviceList = [.. deviceResponse.AllDevices.Select(d => d.Name)]; SelectedDeviceIndex = deviceResponse.BestDevice; } else { SelectedDeviceIndex = 1; // default to first non cpu device } PythonPipList = await RunPythonPipList(); } public async Task ReinstallBackend() { if (Directory.Exists(_pythonService.ModelsDirectory)) { Directory.Delete(_pythonService.ModelsDirectory, true); } if (Directory.Exists(_pythonService.PythonDirectory)) { Directory.Delete(_pythonService.PythonDirectory, true); } await CheckAndExtractBackend(); } public async Task DownloadModels() { BackendSetupMainStatus = "Downloading MangaJaNai Models..."; var download = "https://github.com/the-database/mangajanai/releases/download/1.0.0/MangaJaNai_V1_ModelsOnly.zip"; var targetPath = Path.Join(_pythonService.ModelsDirectory, "mangajanai.zip"); Directory.CreateDirectory(_pythonService.ModelsDirectory); await Downloader.DownloadFileAsync(download, targetPath, (progress) => { BackendSetupMainStatus = $"Downloading MangaJaNai Models ({progress}%)..."; }); BackendSetupMainStatus = "Extracting MangaJaNai Models..."; _pythonService.ExtractZip(targetPath, _pythonService.ModelsDirectory, (double progress) => { BackendSetupMainStatus = $"Extracting MangaJaNai Models ({progress}%)..."; }); File.Delete(targetPath); BackendSetupMainStatus = "Downloading IllustrationJaNai V3denoise Models..."; download = "https://github.com/the-database/MangaJaNai/releases/download/3.0.0/IllustrationJaNai_V3denoise.zip"; targetPath = Path.Join(_pythonService.ModelsDirectory, "illustrationjanai.zip"); await Downloader.DownloadFileAsync(download, targetPath, (progress) => { BackendSetupMainStatus = $"Downloading IllustrationJaNai V3denoise Models ({progress}%)..."; }); BackendSetupMainStatus = "Extracting IllustrationJaNai V3denoise Models..."; _pythonService.ExtractZip(targetPath, _pythonService.ModelsDirectory, (double progress) => { BackendSetupMainStatus = $"Extracting IllustrationJaNai V3denoise Models ({progress}%)..."; }); File.Delete(targetPath); BackendSetupMainStatus = "Downloading IllustrationJaNai V3detail Models..."; download = "https://github.com/the-database/MangaJaNai/releases/download/3.0.0/IllustrationJaNai_V3detail.zip"; targetPath = Path.Join(_pythonService.ModelsDirectory, "illustrationjanai.zip"); await Downloader.DownloadFileAsync(download, targetPath, (progress) => { BackendSetupMainStatus = $"Downloading IllustrationJaNai V3detail Models ({progress}%)..."; }); BackendSetupMainStatus = "Extracting IllustrationJaNai V3detail Models..."; _pythonService.ExtractZip(targetPath, _pythonService.ModelsDirectory, (double progress) => { BackendSetupMainStatus = $"Extracting IllustrationJaNai V3detail Models ({progress}%)..."; }); File.Delete(targetPath); } public async Task InstallUpdatePythonDependencies() { var cmd = _pythonService.InstallUpdatePythonDependenciesCommand; Debug.WriteLine(cmd); // Create a new process to run the CMD command using (var process = new Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = @$"/C {cmd}"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; process.StartInfo.WorkingDirectory = _pythonService.BackendDirectory; var result = string.Empty; using var outputFile = new StreamWriter(Path.Combine(_pythonService.LogsDirectory, "install.log")); outputFile.WriteLine($"Working Directory: {process.StartInfo.WorkingDirectory}"); outputFile.WriteLine($"Run Command: {cmd}"); // Create a StreamWriter to write the output to a log file try { //using var outputFile = new StreamWriter("error.log", append: true); process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { //Debug.WriteLine($"STDERR = {e.Data}"); outputFile.WriteLine(e.Data); BackendSetupSubStatusQueueEnqueue(e.Data); } }; process.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { result = e.Data; outputFile.WriteLine(e.Data); //Debug.WriteLine($"STDOUT = {e.Data}"); BackendSetupSubStatusQueueEnqueue(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Start asynchronous reading of the output await process.WaitForExitAsync(); } catch (IOException) { } } return []; } public void CheckAndDoBackup() { Task.Run(() => { try { if (!File.Exists(_pythonService.AppStatePath)) return; var files = Directory.EnumerateFiles(_pythonService.AppStateFolder) .Where(f => { var name = Path.GetFileName(f); return name.StartsWith("autobackup_") && name.EndsWith(_pythonService.AppStateFilename); }) .OrderByDescending(f => f) .ToList(); var latestBackup = files.FirstOrDefault(); if (latestBackup is not null && FilesAreEqual(_pythonService.AppStatePath, latestBackup)) { return; } var backupName = $"autobackup_{DateTime.Now:yyyyMMdd-HHmmss}_{_pythonService.AppStateFilename}"; var backupPath = Path.Combine(_pythonService.AppStateFolder, backupName); File.Copy(_pythonService.AppStatePath, backupPath); files.Insert(0, backupPath); const int maxBackups = 10; if (files.Count > maxBackups) { foreach (var old in files.Skip(maxBackups)) { try { File.Delete(old); } catch { } } } } catch { } }); } private static bool FilesAreEqual(string path1, string path2) { var info1 = new FileInfo(path1); var info2 = new FileInfo(path2); if (info1.Length != info2.Length) return false; var bytes1 = File.ReadAllBytes(path1); var bytes2 = File.ReadAllBytes(path2); return bytes1.AsSpan().SequenceEqual(bytes2); } public void ResetCurrentWorkflow() { if (CurrentWorkflow != null) { var workflow = JsonConvert.DeserializeObject(DEFAULT_WORKFLOW, NewtonsoftJsonSuspensionDriver.Settings); var workflowIndex = CurrentWorkflow.WorkflowIndex; var workflowName = $"Custom Workflow {workflowIndex}"; if (workflow != null) { var defaultWorkflow = new UpscaleWorkflow { Vm = this, WorkflowIndex = workflowIndex, WorkflowName = workflowName, Chains = workflow.Chains }; foreach (var chain in defaultWorkflow.Chains) { chain.Vm = this; } CurrentWorkflow = defaultWorkflow; } } } public async Task> PopulateDevicesAsync(string? searchText, CancellationToken cancellationToken) { try { var requestUrl = $"https://animejan.ai/mangajanai/api/search?q={Uri.EscapeDataString(searchText?.Trim() ?? "")}&p=0&s=4"; if (string.IsNullOrWhiteSpace(searchText)) { requestUrl = $"https://animejan.ai/mangajanai/api/top"; } var response = await client.GetStringAsync(requestUrl, cancellationToken); var devices = JsonConvert.DeserializeObject>(response, NewtonsoftJsonSuspensionDriver.Settings); if (devices != null) { foreach (var device in devices) { DisplayDeviceMap[device.ToString()] = device; } return devices.ToList(); } } catch (Exception ex) { Debug.WriteLine(ex); } return []; } public async Task CheckForUpdates() { try { if (_updateManagerService.IsInstalled) { await Task.Run(async () => { _update = await _updateManagerService.CheckForUpdatesAsync().ConfigureAwait(true); }); UpdateStatus(); if (AutoUpdateEnabled) { await DownloadUpdate(); } } } catch (Exception ex) { UpdateStatusText = $"Check for update failed: {ex.Message}"; } } public async Task DownloadUpdate() { try { if (_update != null) { ShowDownloadButton = false; await _updateManagerService.DownloadUpdatesAsync(_update, Progress).ConfigureAwait(true); UpdateStatus(); } } catch { } } public void ApplyUpdate() { if (_update != null) { ShowApplyButton = false; _updateManagerService.ApplyUpdatesAndRestart(_update); } } private void UpdateStatus() { ShowDownloadButton = false; ShowApplyButton = false; ShowCheckUpdateButton = true; if (_update != null) { UpdateStatusText = $"Update is available: {_update.TargetFullRelease.Version}"; ShowDownloadButton = true; ShowCheckUpdateButton = false; if (_updateManagerService.IsUpdatePendingRestart) { UpdateStatusText = $"Update ready, pending restart to install version: {_update.TargetFullRelease.Version}"; ShowDownloadButton = false; ShowApplyButton = true; ShowCheckUpdateButton = false; } else { } } else { UpdateStatusText = "No updates found"; } } private void Progress(int percent) { UpdateStatusText = $"Downloading update {_update?.TargetFullRelease.Version} ({percent}%)..."; } public async void OpenModelsDirectory() { await Task.Run(() => { Process.Start("explorer.exe", _pythonService.ModelsDirectory); }); } } [DataContract] public class UpscaleWorkflow : ReactiveObject { public UpscaleWorkflow() { var g1 = this.WhenAnyValue ( x => x.InputFilePath, x => x.OutputFilename, x => x.InputFolderPath, x => x.OutputFolderPath, x => x.SelectedTabIndex, x => x.DisplayDevice, x => x.DisplayPortraitSelected ); var g2 = this.WhenAnyValue ( x => x.UpscaleImages, x => x.UpscaleArchives, x => x.OverwriteExistingFiles, x => x.WebpSelected, x => x.PngSelected, x => x.JpegSelected, x => x.AvifSelected ); var g3 = this.WhenAnyValue ( x => x.ModeFitToDisplaySelected, x => x.ModeHeightSelected, x => x.ModeWidthSelected, x => x.ResizeHeightAfterUpscale, x => x.ResizeWidthAfterUpscale ); g1.CombineLatest(g2).CombineLatest(g3).Subscribe(x => { Validate(); }); this.WhenAnyValue(x => x.Vm).Subscribe(x => { sub?.Dispose(); sub = Vm.WhenAnyValue( x => x.SelectedWorkflowIndex, x => x.RequestShowAppSettings ).Subscribe(x => { this.RaisePropertyChanged(nameof(ActiveWorkflow)); Vm?.RaisePropertyChanged("Workflows"); }); }); this.WhenAnyValue(x => x.InputFilePath).Subscribe(x => { if (string.IsNullOrWhiteSpace(OutputFolderPath) && !string.IsNullOrWhiteSpace(InputFilePath)) { try { OutputFolderPath = Directory.GetParent(InputFilePath)?.ToString() ?? ""; } catch (Exception) { } } }); this.WhenAnyValue(x => x.InputFolderPath).Subscribe(x => { if (string.IsNullOrWhiteSpace(OutputFolderPath) && !string.IsNullOrWhiteSpace(InputFolderPath)) { try { OutputFolderPath = $"{InputFolderPath} mangajanai"; } catch (Exception) { } } }); } private IDisposable? sub; private MainWindowViewModel? _vm; public MainWindowViewModel? Vm { get => _vm; set => this.RaiseAndSetIfChanged(ref _vm, value); } private string _workflowName; [DataMember] public string WorkflowName { get => _workflowName; set => this.RaiseAndSetIfChanged(ref _workflowName, value); } private int _workflowIndex; [DataMember] public int WorkflowIndex { get => _workflowIndex; set => this.RaiseAndSetIfChanged(ref _workflowIndex, value); } public string WorkflowIcon => $"Numeric{WorkflowIndex}Circle"; public bool ActiveWorkflow { get { Debug.WriteLine($"ActiveWorkflow {WorkflowIndex} == {Vm?.SelectedWorkflowIndex}; {Vm == null}"); return WorkflowIndex == Vm?.SelectedWorkflowIndex && (!Vm?.ShowAppSettings ?? false); } } public bool IsDefaultWorkflow => WorkflowIndex == 0; private int _selectedTabIndex; [DataMember] public int SelectedTabIndex { get => _selectedTabIndex; set { if (_selectedTabIndex != value) { this.RaiseAndSetIfChanged(ref _selectedTabIndex, value); Vm?.RaisePropertyChanged(nameof(Vm.InputStatusText)); // TODO } } } private string _inputFilePath = string.Empty; [DataMember] public string InputFilePath { get => _inputFilePath; set { this.RaiseAndSetIfChanged(ref _inputFilePath, value); Vm?.RaisePropertyChanged(nameof(Vm.InputStatusText)); // TODO } } private string _inputFolderPath = string.Empty; [DataMember] public string InputFolderPath { get => _inputFolderPath; set { this.RaiseAndSetIfChanged(ref _inputFolderPath, value); Vm?.RaisePropertyChanged(nameof(Vm.InputStatusText)); // TODO } } private string _outputFilename = "%filename%-mangajanai"; [DataMember] public string OutputFilename { get => _outputFilename; set => this.RaiseAndSetIfChanged(ref _outputFilename, value); } private string _outputFolderPath = string.Empty; [DataMember] public string OutputFolderPath { get => _outputFolderPath; set => this.RaiseAndSetIfChanged(ref _outputFolderPath, value); } private bool _overwriteExistingFiles = false; [DataMember] public bool OverwriteExistingFiles { get => _overwriteExistingFiles; set => this.RaiseAndSetIfChanged(ref _overwriteExistingFiles, value); } private bool _upscaleImages = false; [DataMember] public bool UpscaleImages { get => _upscaleImages; set => this.RaiseAndSetIfChanged(ref _upscaleImages, value); } private bool _upscaleArchives = true; [DataMember] public bool UpscaleArchives { get => _upscaleArchives; set => this.RaiseAndSetIfChanged(ref _upscaleArchives, value); } private int? _resizeHeightAfterUpscale = 2160; [DataMember] public int? ResizeHeightAfterUpscale { get => _resizeHeightAfterUpscale; set => this.RaiseAndSetIfChanged(ref _resizeHeightAfterUpscale, value ?? 2160); } private int? _resizeWidthAfterUpscale = 3840; [DataMember] public int? ResizeWidthAfterUpscale { get => _resizeWidthAfterUpscale; set => this.RaiseAndSetIfChanged(ref _resizeWidthAfterUpscale, value ?? 3840); } private bool _webpSelected = true; [DataMember] public bool WebpSelected { get => _webpSelected; set { this.RaiseAndSetIfChanged(ref _webpSelected, value); this.RaisePropertyChanged(nameof(ShowUseLosslessCompression)); this.RaisePropertyChanged(nameof(ShowLossyCompressionQuality)); } } private bool _avifSelected = false; [DataMember] public bool AvifSelected { get => _avifSelected; set { this.RaiseAndSetIfChanged(ref _avifSelected, value); this.RaisePropertyChanged(nameof(ShowLossyCompressionQuality)); this.RaisePropertyChanged(nameof(ShowUseLosslessCompression)); } } private bool _pngSelected = false; [DataMember] public bool PngSelected { get => _pngSelected; set { this.RaiseAndSetIfChanged(ref _pngSelected, value); } } private bool _jpegSelected = false; [DataMember] public bool JpegSelected { get => _jpegSelected; set { this.RaiseAndSetIfChanged(ref _jpegSelected, value); this.RaisePropertyChanged(nameof(ShowLossyCompressionQuality)); } } public string ImageFormat => WebpSelected ? "webp" : PngSelected ? "png" : AvifSelected ? "avif" : "jpg"; public bool ShowUseLosslessCompression => WebpSelected; private bool _useLosslessCompression = false; [DataMember] public bool UseLosslessCompression { get => _useLosslessCompression; set { this.RaiseAndSetIfChanged(ref _useLosslessCompression, value); this.RaisePropertyChanged(nameof(ShowLossyCompressionQuality)); } } public bool ShowLossyCompressionQuality => JpegSelected || (WebpSelected && !UseLosslessCompression) || AvifSelected; private int? _lossyCompressionQuality = 80; [DataMember] public int? LossyCompressionQuality { get => _lossyCompressionQuality; set => this.RaiseAndSetIfChanged(ref _lossyCompressionQuality, value ?? 80); } private bool _showLossySettings = true; [DataMember] public bool ShowLossySettings { get => _showLossySettings; set => this.RaiseAndSetIfChanged(ref _showLossySettings, value); } private bool _modeScaleSelected = true; [DataMember] public bool ModeScaleSelected { get => _modeScaleSelected; set { this.RaiseAndSetIfChanged(ref _modeScaleSelected, value); } } private int _upscaleScaleFactor = 4; [DataMember] public int UpscaleScaleFactor { get => _upscaleScaleFactor; set { this.RaiseAndSetIfChanged(ref _upscaleScaleFactor, value); this.RaisePropertyChanged(nameof(Is1x)); this.RaisePropertyChanged(nameof(Is2x)); this.RaisePropertyChanged(nameof(Is3x)); this.RaisePropertyChanged(nameof(Is4x)); } } public bool Is1x => UpscaleScaleFactor == 1; public bool Is2x => UpscaleScaleFactor == 2; public bool Is3x => UpscaleScaleFactor == 3; public bool Is4x => UpscaleScaleFactor == 4; public void SetUpscaleScaleFactor(int scaleFactor) { UpscaleScaleFactor = scaleFactor; } private bool _modeWidthSelected = false; [DataMember] public bool ModeWidthSelected { get => _modeWidthSelected; set { this.RaiseAndSetIfChanged(ref _modeWidthSelected, value); } } private bool _modeHeightSelected = false; [DataMember] public bool ModeHeightSelected { get => _modeHeightSelected; set { this.RaiseAndSetIfChanged(ref _modeHeightSelected, value); } } private bool _modeFitToDisplaySelected = false; [DataMember] public bool ModeFitToDisplaySelected { get => _modeFitToDisplaySelected; set { this.RaiseAndSetIfChanged(ref _modeFitToDisplaySelected, value); } } private string _displayDevice; [DataMember] public string DisplayDevice { get => _displayDevice; set { this.RaiseAndSetIfChanged(ref _displayDevice, value); this.RaisePropertyChanged(nameof(DisplayDeviceWidth)); this.RaisePropertyChanged(nameof(DisplayDeviceHeight)); } } [DataMember] public int DisplayDeviceWidth { get { if (Vm != null && DisplayDevice != null) { Vm.DisplayDeviceMap.TryGetValue(DisplayDevice, out var displayDevice); if (displayDevice != null) { return DisplayPortraitSelected ? displayDevice.Width : displayDevice.Height; } } return 0; } } [DataMember] public int DisplayDeviceHeight { get { if (Vm != null && DisplayDevice != null) { Vm.DisplayDeviceMap.TryGetValue(DisplayDevice, out var displayDevice); if (displayDevice != null) { return DisplayPortraitSelected ? displayDevice.Height : displayDevice.Width; } } return 0; } } private bool _displayPortraitSelected = true; [DataMember] public bool DisplayPortraitSelected { get => _displayPortraitSelected; set { this.RaiseAndSetIfChanged(ref _displayPortraitSelected, value); this.RaisePropertyChanged(nameof(DisplayDeviceWidth)); this.RaisePropertyChanged(nameof(DisplayDeviceHeight)); } } private bool _showAdvancedSettings = false; [DataMember] public bool ShowAdvancedSettings { get => _showAdvancedSettings; set => this.RaiseAndSetIfChanged(ref _showAdvancedSettings, value); } private int _grayscaleDetectionThreshold = 12; [DataMember] public int GrayscaleDetectionThreshold { get => _grayscaleDetectionThreshold; set => this.RaiseAndSetIfChanged(ref _grayscaleDetectionThreshold, value); } private AvaloniaList _chains; [DataMember] public AvaloniaList Chains { get => _chains; set => this.RaiseAndSetIfChanged(ref _chains, value); } private bool _valid = false; [IgnoreDataMember] public bool Valid { get => _valid; set { this.RaiseAndSetIfChanged(ref _valid, value); if (Vm != null) { Vm.RaisePropertyChanged(nameof(Vm.UpscaleEnabled)); // TODO Vm.RaisePropertyChanged(nameof(Vm.LeftStatus)); // TODO } } } public void SetWebpSelected() { WebpSelected = true; PngSelected = false; JpegSelected = false; AvifSelected = false; } public void SetPngSelected() { PngSelected = true; WebpSelected = false; JpegSelected = false; AvifSelected = false; } public void SetJpegSelected() { JpegSelected = true; WebpSelected = false; PngSelected = false; AvifSelected = false; } public void SetAvifSelected() { AvifSelected = true; JpegSelected = false; WebpSelected = false; PngSelected = false; } public void SetModeScaleSelected() { ModeScaleSelected = true; ModeWidthSelected = false; ModeHeightSelected = false; ModeFitToDisplaySelected = false; } public void SetModeWidthSelected() { ModeWidthSelected = true; ModeScaleSelected = false; ModeHeightSelected = false; ModeFitToDisplaySelected = false; } public void SetModeHeightSelected() { ModeHeightSelected = true; ModeScaleSelected = false; ModeWidthSelected = false; ModeFitToDisplaySelected = false; } public void SetModeFitToDisplaySelected() { ModeFitToDisplaySelected = true; ModeHeightSelected = false; ModeWidthSelected = false; ModeScaleSelected = false; } public void Validate() { var valid = true; var validationText = new List(); if (SelectedTabIndex == 0) { if (string.IsNullOrWhiteSpace(InputFilePath)) { valid = false; validationText.Add("Input File is required."); } else if (!File.Exists(InputFilePath)) { valid = false; validationText.Add("Input File does not exist."); } } else { if (string.IsNullOrWhiteSpace(InputFolderPath)) { valid = false; validationText.Add("Input Folder is required."); } else if (!Directory.Exists(InputFolderPath)) { valid = false; validationText.Add("Input Folder does not exist."); } } if (string.IsNullOrWhiteSpace(OutputFilename)) { valid = false; validationText.Add("Output Filename is required."); } if (string.IsNullOrWhiteSpace(OutputFolderPath)) { valid = false; validationText.Add("Output Folder is required."); } if (ModeHeightSelected && ResizeHeightAfterUpscale == 0) { valid = false; validationText.Add("Output Height is invalid. Enter a height larger than 0."); } if (ModeWidthSelected && ResizeWidthAfterUpscale == 0) { valid = false; validationText.Add("Output Width is invalid. Enter a width larger than 0."); } if (ModeFitToDisplaySelected && (DisplayDeviceWidth == 0 || DisplayDeviceHeight == 0)) { valid = false; validationText.Add("Tablet Device or Display is invalid. Please make a selection from the list of options."); } Valid = valid; if (Vm != null) { // TODO Vm.CheckInputs(); if (Vm?.ProgressTotalFiles == 0) { Valid = false; validationText.Add($"{Vm?.InputStatusText} selected for upscaling. At least one file must be selected."); } Vm.ValidationText = string.Join("\n", validationText); } } } [DataContract] public class UpscaleChain : ReactiveObject { IPythonService _pythonService; public UpscaleChain(IPythonService? pythonService = null) { _pythonService = pythonService ?? Locator.Current.GetService()!; this.WhenAnyValue(x => x.Vm).Subscribe(x => { sub?.Dispose(); sub = Vm.WhenAnyValue( x => x.IsExtractingBackend ).Subscribe(x => { this.RaisePropertyChanged(nameof(AllModels)); this.RaisePropertyChanged(nameof(ModelFilePath)); }); }); this.RaisePropertyChanged(nameof(AllModels)); this.RaisePropertyChanged(nameof(ModelFilePath)); } private IDisposable? sub; private MainWindowViewModel? _vm; public MainWindowViewModel? Vm { get => _vm; set => this.RaiseAndSetIfChanged(ref _vm, value); } private string _chainNumber = string.Empty; [DataMember] public string ChainNumber { get => _chainNumber; set => this.RaiseAndSetIfChanged(ref _chainNumber, value); } private string _minResolution = "0x0"; [DataMember] public string MinResolution { get => _minResolution; set => this.RaiseAndSetIfChanged(ref _minResolution, value); } private string _maxResolution = "0x0"; [DataMember] public string MaxResolution { get => _maxResolution; set => this.RaiseAndSetIfChanged(ref _maxResolution, value); } private bool _isGrayscale = false; [DataMember] public bool IsGrayscale { get => _isGrayscale; set => this.RaiseAndSetIfChanged(ref _isGrayscale, value); } private bool _isColor = false; [DataMember] public bool IsColor { get => _isColor; set => this.RaiseAndSetIfChanged(ref _isColor, value); } private int? _minScaleFactor = 0; [DataMember] public int? MinScaleFactor { get => _minScaleFactor; set => this.RaiseAndSetIfChanged(ref _minScaleFactor, value ?? 0); } private int? _maxScaleFactor = 0; [DataMember] public int? MaxScaleFactor { get => _maxScaleFactor; set => this.RaiseAndSetIfChanged(ref _maxScaleFactor, value ?? 0); } private string _modelFilePath = string.Empty; [DataMember] public string ModelFilePath { get => _modelFilePath; set => this.RaiseAndSetIfChanged(ref _modelFilePath, value); } private string _modelTileSize = "Auto (Estimate)"; [DataMember] public string ModelTileSize { get => _modelTileSize; set => this.RaiseAndSetIfChanged(ref _modelTileSize, value); } private bool _autoAdjustLevels = false; [DataMember] public bool AutoAdjustLevels { get => _autoAdjustLevels; set => this.RaiseAndSetIfChanged(ref _autoAdjustLevels, value); } private int? _resizeHeightBeforeUpscale = 0; [DataMember] public int? ResizeHeightBeforeUpscale { get => _resizeHeightBeforeUpscale; set => this.RaiseAndSetIfChanged(ref _resizeHeightBeforeUpscale, value ?? 0); } private int? _resizeWidthBeforeUpscale = 0; [DataMember] public int? ResizeWidthBeforeUpscale { get => _resizeWidthBeforeUpscale; set => this.RaiseAndSetIfChanged(ref _resizeWidthBeforeUpscale, value ?? 0); } private double? _resizeFactorBeforeUpscale = 100; [DataMember] public double? ResizeFactorBeforeUpscale { get => _resizeFactorBeforeUpscale; set => this.RaiseAndSetIfChanged(ref _resizeFactorBeforeUpscale, value ?? 100); } public AvaloniaList AllModels => _pythonService.AllModels; private string[] _tileSizes = [ "Auto (Estimate)", "Maximum", "No Tiling", "128", "192", "256", "384", "512", "768", "1024", "2048", "4096"]; public string[] TileSizes { get => _tileSizes; set => this.RaiseAndSetIfChanged(ref _tileSizes, value); } } // TODO refactor into separate file public class ReaderDevice { public string Name { get; set; } = default!; public string Brand { get; set; } = default!; public string Year { get; set; } = default!; public int Width { get; set; } = default!; public int Height { get; set; } = default!; public override string ToString() { List parts = []; if (!string.IsNullOrWhiteSpace(Brand)) { parts.Add(Brand); } if (!string.IsNullOrWhiteSpace(Name)) { parts.Add(Name); } if (!string.IsNullOrWhiteSpace(Year)) { parts.Add($"({Year})"); } return string.Join(" ", parts); } } public class DeviceResponse { [JsonProperty("all_devices")] public List AllDevices { get; set; } = []; [JsonProperty("best_device")] public int BestDevice { get; set; } } public class AcceleratorDevice { [JsonProperty("type")] public string Type { get; set; } = string.Empty; [JsonProperty("index")] public int Index { get; set; } [JsonProperty("name")] public string Name { get; set; } = string.Empty; [JsonProperty("device_string")] public string DeviceString { get; set; } = string.Empty; [JsonProperty("supports_fp16")] public bool SupportsFp16 { get; set; } [JsonProperty("supports_bf16")] public bool SupportsBf16 { get; set; } [JsonProperty("memory_total")] public long? MemoryTotal { get; set; } [JsonProperty("memory_free")] public long? MemoryFree { get; set; } } } ================================================ FILE: MangaJaNaiConverterGui/ViewModels/ViewModelBase.cs ================================================ using ReactiveUI; namespace MangaJaNaiConverterGui.ViewModels { //[DataContract] public class ViewModelBase : ReactiveObject { //private bool _autoUpdate; //[DataMember] //public bool AutoUpdateEnabled //{ // get => _autoUpdate; // set => this.RaiseAndSetIfChanged(ref _autoUpdate, value); //} } } ================================================ FILE: MangaJaNaiConverterGui/Views/MainWindow.axaml ================================================ Default Workflows Custom Workflows Console Workflow Name Single File Upscale Input File The upscaling model to run. To choose from more models, add PyTorch (*.pth) model files to the models directory. Select No Model to skip running any upscaling model for this chain. Model Tile Size px Tile size to use when upscaling images with the selected model. The image is cut into tiles in order to upscale without running into the VRAM limits of your GPU. Larger is better when the GPU has enough VRAM to support it. The auto setting estimates the largest tile size which can be used based on available VRAM and is recommended for most users. A chain is a a set of upscale settings which can be activated based on conditions such as the image resolution and whether the image is color or grayscale. This allows you to specify different upscale models for different types of images. Auto Update Whether to automatically check for and install app updates. App is not installed; auto update settings unavailable. Device Which device to use for upscaling with PyTorch. CPU is much slower than GPU and should be avoided unless no GPU is available. FP16 Mode Runs PyTorch upscaling in FP16 mode for less VRAM usage and speedup on RTX GPUs.