Skip to content

Commit

Permalink
Merge pull request #7 from imxcstar/main
Browse files Browse the repository at this point in the history
分离出asp.netcore,项目名字修改
  • Loading branch information
feiyun0112 authored Jun 6, 2024
2 parents 73dcb2e + 8d02058 commit 561aa87
Show file tree
Hide file tree
Showing 23 changed files with 444 additions and 319 deletions.
15 changes: 15 additions & 0 deletions Demo.AspNetCore/Demo.AspNetCore.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Demo\Demo.csproj" />
<ProjectReference Include="..\Gradio.Net.AspNetCore\Gradio.Net.AspNetCore.csproj" />
</ItemGroup>

</Project>
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
25 changes: 25 additions & 0 deletions Gradio.Net.AspNetCore/App.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gradio.Net
{
public static class App
{
public static void Launch(Blocks blocks, Action<GradioServiceConfig>? additionalConfigurationAction = null, params string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddGradio();

WebApplication app = builder.Build();

app.UseGradio(blocks, additionalConfigurationAction);

app.Run();
}
}
}
24 changes: 24 additions & 0 deletions Gradio.Net.AspNetCore/EventWorker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gradio.Net.AspNetCore
{
internal class EventWorker : BackgroundService
{
private readonly GradioApp _gradioApp;

public EventWorker(GradioApp gradioApp)
{
_gradioApp = gradioApp;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await _gradioApp.StartEventLoopAsync(stoppingToken);
}
}
}
32 changes: 32 additions & 0 deletions Gradio.Net.AspNetCore/FileMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gradio.Net.AspNetCore
{
internal class FileMiddleware
{
private readonly RequestDelegate _next;

public FileMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext httpContext, GradioApp gradioApp)
{
string path = httpContext.Request.Path.ToString();
const string FILE_URL = "/file=";
if (path.StartsWith(FILE_URL))
{
(string filePath, string contentType) = await gradioApp.GetUploadedFile(path.Substring(FILE_URL.Length));
await httpContext.Response.SendFileAsync(filePath);
return;
}
await _next(httpContext);
}
}
}
41 changes: 41 additions & 0 deletions Gradio.Net.AspNetCore/Gradio.Net.AspNetCore.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageId>Gradio.Net.AspNetCore</PackageId>
<Version>0.0.9</Version>
<Title>Gradio.Net</Title>
<Authors>feiyun0112</Authors>
<Description>Gradio for .NET – a port of Gradio, an open-source Python package that allows you to quickly build a demo or web application for your machine learning model, API, or any arbitrary Python function. Gradio for .NET – 基于 Gradio 的 .NET 移植,Gradio 是一个开源 Python 包,允许你为机器学习模型、API 或任何任意 Python 函数快速构建演示或 Web 应用程序。</Description>
<ProjectUrl>https://github.com/feiyun0112/Gradio.Net</ProjectUrl>
<Tags>Gradio, UI, UI-Components</Tags>
<RepositoryUrl>https://github.com/feiyun0112/Gradio.Net</RepositoryUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>

<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<RequireLicenseAcceptance>false</RequireLicenseAcceptance>
<PackageRequireLicenseAcceptance>False</PackageRequireLicenseAcceptance>
</PropertyGroup>

<ItemGroup>
<ProjectCapability Include="AspNetCore" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Gradio.Net\Gradio.Net.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Gradio.Net.Models;
using Gradio.Net.AspNetCore;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;


namespace Microsoft.AspNetCore.Builder;

public static class GradioServiceExtensions
{

internal static string GetRootUrl(this HttpRequest httpRequest)
{
return $"{httpRequest.Scheme}://{httpRequest.Host}";
}

public static IServiceCollection AddGradio(this IServiceCollection services)
{
services.Configure<IISServerOptions>(options =>
Expand All @@ -33,7 +37,7 @@ public static IServiceCollection AddGradio(this IServiceCollection services)
x.MultipartHeadersLengthLimit = int.MaxValue;
});

services.AddSingleton<App>(new App());
services.AddSingleton<GradioApp>(new GradioApp());
services.AddHostedService<EventWorker>();
return services;
}
Expand All @@ -46,93 +50,76 @@ public static WebApplication UseGradio(this WebApplication webApplication
GradioServiceConfig gradioServiceConfig = new();
additionalConfigurationAction?.Invoke(gradioServiceConfig);

App app = webApplication.Services.GetRequiredService<App>();
GradioApp gradioApp = webApplication.Services.GetRequiredService<GradioApp>();

app.SetConfig(gradioServiceConfig);

gradioApp.SetConfig(gradioServiceConfig);

StaticFileProvider fileProvider = new(@"templates/frontend");
StaticFileProvider fileProvider = new(gradioApp);
webApplication.UseStaticFiles(new StaticFileOptions
{
FileProvider = fileProvider
});

webApplication.MapGet("/", (HttpRequest request, [FromServices] App app) =>
webApplication.MapGet("/", (HttpRequest request, [FromServices] GradioApp app) =>
{
Template template = new(new StreamReader(fileProvider.GetFileInfo("index.html").CreateReadStream()).ReadToEnd());
return Results.Content(template.Render(new Dictionary<string, object>() { { "config", app.GetConfig(request) } }), "text/html");
return Results.Content(template.Render(new Dictionary<string, object>() { { "config", app.GetConfig(request.GetRootUrl()) } }), "text/html");
});

webApplication.MapGet("/config", (HttpRequest request, [FromServices] App app) =>
webApplication.MapGet("/config", (HttpRequest request, [FromServices] GradioApp app) =>
{
return app.GetConfig(request);
return app.GetConfig(request.GetRootUrl());
});

webApplication.MapGet("/info", (HttpRequest request, [FromServices] App app) =>
webApplication.MapGet("/info", (HttpRequest request, [FromServices] GradioApp app) =>
{
return app.GetApiInfo(request);
return app.GetApiInfo();
});

webApplication.MapPost("/queue/join", async (HttpRequest request, PredictBodyIn body, [FromServices] App app) =>
webApplication.MapPost("/queue/join", async (HttpRequest request, PredictBodyIn body, [FromServices] GradioApp app) =>
{
return await app.QueueJoin(request, body);
return await app.QueueJoin(request.GetRootUrl(), body);
});

webApplication.MapGet("/queue/data", async ([FromServices] App app,HttpContext context, CancellationToken stoppingToken) =>
{
context.Response.Headers.Add("Content-Type", "text/event-stream");
webApplication.MapGet("/queue/data", async ([FromServices] GradioApp app, HttpContext context, CancellationToken stoppingToken) =>
{
context.Response.Headers.Add("Content-Type", "text/event-stream");
StreamWriter streamWriter = new(context.Response.Body);
var sessionHash = context.Request.Query["session_hash"].FirstOrDefault();
await foreach (SSEMessage message in app.QueueData(sessionHash, stoppingToken))
{
await streamWriter.WriteLineAsync(message.ProcessMsg());
await streamWriter.FlushAsync();
}
await streamWriter.WriteLineAsync(new CloseStreamMessage().ProcessMsg());
StreamWriter streamWriter = new(context.Response.Body);
var sessionHash = context.Request.Query["session_hash"].FirstOrDefault();
await foreach (SSEMessage message in app.QueueData(sessionHash, stoppingToken))
{
await streamWriter.WriteLineAsync(message.ProcessMsg());
await streamWriter.FlushAsync();
Context.PendingEventIdsSession.TryRemove(sessionHash, out _);
});
}
await streamWriter.WriteLineAsync(new CloseStreamMessage().ProcessMsg());
await streamWriter.FlushAsync();
app.ClonseSession(sessionHash);
});

webApplication.MapPost("/upload", async (HttpRequest request, [FromServices] App app) =>
webApplication.MapPost("/upload", async (HttpRequest request, [FromServices] GradioApp app) =>
{
string? uploadId = request.Query["upload_id"].First();
IFormFileCollection files = request.Form.Files;
return await app.Upload(uploadId, files);
return await app.Upload(uploadId, files.Select(x => (x.OpenReadStream(), x.FileName)).ToList());
});

webApplication.MapGet("/upload_progress", async ([FromServices] App app, HttpContext context, CancellationToken stoppingToken) =>
webApplication.MapGet("/upload_progress", async ([FromServices] GradioApp app, HttpContext context, CancellationToken stoppingToken) =>
{
context.Response.Headers.Add("Content-Type", "text/event-stream");
StreamWriter streamWriter = new(context.Response.Body);
await streamWriter.WriteLineAsync(new DoneMessage().ProcessMsg());
await streamWriter.FlushAsync();
});



webApplication.MapGet("/file", async ([FromServices] App app, HttpContext context) =>
webApplication.MapGet("/file", ([FromServices] GradioApp app, HttpContext context) =>
{
return context.Request.Path;
//await app.GetUploadedFile(pathOrUrl);
});

return webApplication;
}

private static Dictionary<string, object> GetConfig(HttpRequest request)
{
Dictionary<string, object> config = [];
return config;
}

private static string GetTemplate(string rootPath)
{
string file = Path.Combine(rootPath, @"templates\frontend\index.html");

return File.ReadAllText(file);
}
}
36 changes: 36 additions & 0 deletions Gradio.Net.AspNetCore/StaticFileProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.Extensions.FileProviders.Embedded;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Gradio.Net.AspNetCore
{
internal class StaticFileProvider : IFileProvider
{
private readonly GradioApp _gradioApp;

internal StaticFileProvider(GradioApp gradioApp)
{
_gradioApp = gradioApp;
}

public IFileInfo GetFileInfo(string subpath)
{
return _gradioApp.GetFileInfo(subpath);
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
return null;
}

public IChangeToken Watch(string filter)
{
return null;
}
}
}
27 changes: 12 additions & 15 deletions Gradio.Net.sln
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,22 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "demo", "demo\demo.csproj", "{AB717BDB-6555-44AA-A367-0EC05A13E8F0}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Demo.AspNetCore", "Demo.AspNetCore\Demo.AspNetCore.csproj", "{AB717BDB-6555-44AA-A367-0EC05A13E8F0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gradio.Net", "Gradio.Net\Gradio.Net.csproj", "{9E717197-6897-4C77-87D4-1C3161A4C6BD}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B9049476-4AC5-4960-A33D-472400F5E820}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
LICENSE = LICENSE
README.md = README.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{27EAD232-B473-497C-9475-6F3873026A90}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gradio.Net.AspNetCore", "Gradio.Net.AspNetCore\Gradio.Net.AspNetCore.csproj", "{C1AEB66B-E9A6-4EAC-B605-B79CA1269BC1}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{141EB74D-8960-4465-879A-69618C24D710}"
ProjectSection(SolutionItems) = preProject
.github\workflows\main.yml = .github\workflows\main.yml
EndProjectSection
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Demo", "Demo\Demo.csproj", "{059D3B12-6259-4E0A-B61D-4DFA59074296}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "readme_files", "readme_files", "{D270B5CB-D16A-4C8D-8A7B-0EFBDC6918E8}"
ProjectSection(SolutionItems) = preProject
readme_files\chatbot_demo.md = readme_files\chatbot_demo.md
readme_files\form_demo.md = readme_files\form_demo.md
readme_files\media_demo.md = readme_files\media_demo.md
readme_files\layout_demo.md = readme_files\layout_demo.md
readme_files\media_demo.md = readme_files\media_demo.md
readme_files\progress_demo.md = readme_files\progress_demo.md
readme_files\README_zh-cn.md = readme_files\README_zh-cn.md
EndProjectSection
Expand All @@ -45,13 +37,18 @@ Global
{9E717197-6897-4C77-87D4-1C3161A4C6BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E717197-6897-4C77-87D4-1C3161A4C6BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E717197-6897-4C77-87D4-1C3161A4C6BD}.Release|Any CPU.Build.0 = Release|Any CPU
{C1AEB66B-E9A6-4EAC-B605-B79CA1269BC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C1AEB66B-E9A6-4EAC-B605-B79CA1269BC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C1AEB66B-E9A6-4EAC-B605-B79CA1269BC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C1AEB66B-E9A6-4EAC-B605-B79CA1269BC1}.Release|Any CPU.Build.0 = Release|Any CPU
{059D3B12-6259-4E0A-B61D-4DFA59074296}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{059D3B12-6259-4E0A-B61D-4DFA59074296}.Debug|Any CPU.Build.0 = Debug|Any CPU
{059D3B12-6259-4E0A-B61D-4DFA59074296}.Release|Any CPU.ActiveCfg = Release|Any CPU
{059D3B12-6259-4E0A-B61D-4DFA59074296}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{141EB74D-8960-4465-879A-69618C24D710} = {27EAD232-B473-497C-9475-6F3873026A90}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A68FA315-516B-4431-9B4B-E2C75C3D527E}
EndGlobalSection
Expand Down
Loading

0 comments on commit 561aa87

Please sign in to comment.