经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
Gradio.NET 支持 .NET 8 简化 Web 应用开发
来源:cnblogs  作者:小码编匠  时间:2024/8/26 10:33:48  对本文有异议

前言

Gradio.NET 是 Gradio 在 .NET 平台上的移植版本。Gradio 是一个开源的 Python 包,用于快速构建机器学习模型、API 或任意 Python 函数的演示或 Web 应用程序。

Gradio.NET 继承了 Gradio 的核心理念,以.NET 开发习惯和熟悉的方式进行Web应用开发,其主要特点包括:

  • 易用性:只需几行 .NET 代码即可创建功能完善的用户界面。

  • 灵活性:支持多种类型的输入和输出,包括文本、图像、音频等。

  • 一键分享:轻松生成访问链接,方便进行测试和使用。

  • 集成支持:能够无缝集成到主流的 .NET 框架和库中,如 ASP.NET Core 和 Entity Framework,加速开发和部署流程。

总而言之,Gradio.NET 是一个强大的工具,极大地简化了创建和分享界面的过程,使我们能够专注于业务逻辑而无需担心复杂的前端开发工作。

Gradio.NET

Gradio.NET 是一个基于 Gradio 的 .NET 实现,我们无需掌握任何前端技术(如 JavaScript、CSS 或 HTML),仅用几行 .NET 代码就能快速构建机器学习模型、API 或任意函数的演示或 Web 应用程序。

通过 Gradio.NET,可以轻松创建美观的交互式 Web 界面,无需前端开发经验。

Gradio.NET 使用

1、创建项目

创建一个新的 .NET 8 WebAPI 标准项目,选择启用 OpenAPI 支持和使用控制器;

  1. dotnet new webapi -n ManageCore.Api
  2. cd ManageCore.Api

2、安装 Gradio.Net

安装 NuGet 包 Gradio.Net.AspNetCore 这个包。

3、示例代码

在 Program.cs 中输入以下示例代码:

  1. App.Launch(await CreateBlocks());
  2. ?
  3. async Task<Blocks> CreateBlocks()
  4. {
  5. using (var blocks = gr.Blocks())
  6. {
  7. gr.Markdown("开始在下面键入,然后点击**运行** 查看输出结果.");
  8. Textbox input, output;
  9. using (gr.Row())
  10. {
  11. input = gr.Textbox(placeholder: "你叫什么名字?");
  12. output = gr.Textbox();
  13. }
  14. var btn = gr.Button("运行");
  15. await btn.Click(fn: async (input) => gr.Output($"欢迎使用 Gradio.Net, {input.Data[0]}!"), inputs: new[] { input }, outputs: new[] { output });
  16. ?
  17. return blocks;
  18. }
  19. }

运行结果如下图所示:

如果想在现有项目中使用 Gradio.NET

可以使用AddGradioUseGradio扩展方法:

  1. var builder = WebApplication.CreateBuilder(args);
  2. builder.Services.AddGradio();
  3. ?
  4. var app = builder.Build();
  5. ?
  6. app.UseGradio(await CreateBlocks());
  7. ?
  8. app.Run();

Gradio.NET 示例

1、Layout

Gradio.NET 常用的布局方式都包括:Row/Column、Tab、Group、Accordion等。

示例代码

  1. App.Launch(await CreateBlocks());
  2. ?
  3. async Task<Blocks> CreateBlocks()
  4. {
  5. using (var blocks = gr.Blocks())
  6. {
  7. gr.Markdown("# Layout Demo");
  8. ?
  9. gr.Markdown("## Row/Column");
  10. using (gr.Row())
  11. {
  12. using (gr.Column(scale: 1))
  13. {
  14. var text1 = gr.Textbox();
  15. var text2 = gr.Textbox();
  16. }
  17. ?
  18. using (gr.Column(scale: 4))
  19. {
  20. var btn1 = gr.Button("Button 1");
  21. var btn2 = gr.Button("Button 2");
  22. }
  23. }
  24. ?
  25. gr.Markdown("## Tab");
  26. using (gr.Tab("Lion"))
  27. {
  28. gr.Textbox("lion");
  29. gr.Button("New Lion");
  30. }
  31. using (gr.Tab("Tiger"))
  32. {
  33. gr.Textbox("tiger");
  34. gr.Button("New Tiger");
  35. }
  36. ?
  37. gr.Markdown("## Group");
  38. using (gr.Group())
  39. {
  40. gr.Textbox(label: "First");
  41. gr.Textbox(label: "Last");
  42. }
  43. ?
  44. gr.Markdown("## Accordion");
  45. using (gr.Accordion("See Details"))
  46. {
  47. gr.Markdown("lorem ipsum");
  48. }
  49. ?
  50. return blocks;
  51. }
  52. }

示例效果

2、Form

表单示例代码,具体如下:

  1. App.Launch(await CreateBlocks());
  2. ?
  3. async Task<Blocks> CreateBlocks()
  4. {
  5. using (var blocks = gr.Blocks())
  6. {
  7. using (gr.Column())
  8. {
  9. var text1 = gr.Textbox();
  10. var dropdown1 = gr.Dropdown(choices: new[] { "First Choice", "Second Choice", "Third Choice" });
  11. var checkbox1 = gr.Checkbox();
  12. var checkboxGroup1 = gr.CheckboxGroup(choices: new[] { "First Choice", "Second Choice", "Third Choice" });
  13. var multimodalTextbox1 = gr.MultimodalTextbox(interactive:true);
  14. var number1 = gr.Number();
  15. var radio1 = gr.Radio(choices: ["First Choice", "Second Choice", "Third Choice"]);
  16. var slider1 = gr.Slider();
  17. ?
  18. var text_Result = gr.Textbox(label:"Form Value", interactive:false);
  19. var btn = gr.Button("Run");
  20. await btn.Click(fn: async (input) => gr.Output($@"
  21. Textbox: {Textbox.Payload(input.Data[0])}
  22. Dropdown: {string.Join(", ",Dropdown.Payload(input.Data[1]))}
  23. Checkbox: {Checkbox.Payload(input.Data[2])}
  24. CheckboxGroup: {string.Join(", ", CheckboxGroup.Payload(input.Data[3]))}
  25. MultimodalTextbox: {MultimodalTextbox.Payload(input.Data[4]).Files.FirstOrDefault()?.OrigName}
  26. Number: {Number.Payload(input.Data[5])}
  27. Radio: {string.Join(", ", Radio.Payload(input.Data[6]))}
  28. Slider: {Slider.Payload(input.Data[7])}
  29. "), inputs: new Component[] { text1, dropdown1, checkbox1, checkboxGroup1, multimodalTextbox1, number1, radio1, slider1 }, outputs: new[] { text_Result });
  30. }
  31. ?
  32. return blocks;
  33. }
  34. }

示例效果

3、Media

多媒体控件,具体参考代码

  1. App.Launch(await CreateBlocks());
  2. ?
  3. async Task<Blocks> CreateBlocks()
  4. {
  5. using (var blocks = gr.Blocks())
  6. {
  7. gr.Markdown("**Image Demo** upload a image and click button");
  8. Gradio.Net.Image input, output;
  9. using (gr.Row())
  10. {
  11. input = gr.Image();
  12. output = gr.Image();
  13. }
  14. var btn = gr.Button("Submit");
  15. await btn.Click(fn: async (input) => gr.Output(DrawWaterMarkOnImage(Gradio.Net.Image.Payload(input.Data[0]))), inputs: new[] { input }, outputs: new[] { output });
  16. ?
  17. return blocks;
  18. }
  19. }
  20. ?
  21. ?
  22. static string DrawWaterMarkOnImage(string inputImageFilePath)
  23. {
  24. using (var img = SixLabors.ImageSharp.Image.Load(inputImageFilePath))
  25. {
  26. var outputFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png");
  27. Font font = SystemFonts.CreateFont("Arial", 10); // for scaling water mark size is largely ignored.
  28. ?
  29. using (var img2 = img.Clone(ctx => ApplyScalingWaterMarkSimple(ctx, font, "Gradio.Net", Color.HotPink, 5)))
  30. {
  31. img2.Save(outputFilePath);
  32. }
  33. return outputFilePath;
  34. }
  35. ?
  36. }
  37. static IImageProcessingContext ApplyScalingWaterMarkSimple(IImageProcessingContext processingContext,
  38. Font font,
  39. string text,
  40. Color color,
  41. float padding)
  42. {
  43. Size imgSize = processingContext.GetCurrentSize();
  44. ?
  45. float targetWidth = imgSize.Width - (padding * 2);
  46. float targetHeight = imgSize.Height - (padding * 2);
  47. ?
  48. // Measure the text size
  49. FontRectangle size = TextMeasurer.MeasureSize(text, new TextOptions(font));
  50. ?
  51. // Find out how much we need to scale the text to fill the space (up or down)
  52. float scalingFactor = Math.Min(targetWidth / size.Width, targetHeight / size.Height);
  53. ?
  54. // Create a new font
  55. Font scaledFont = new Font(font, scalingFactor * font.Size);
  56. ?
  57. var center = new PointF(imgSize.Width / 2, imgSize.Height / 2);
  58. var textOptions = new RichTextOptions(scaledFont)
  59. {
  60. Origin = center,
  61. HorizontalAlignment = HorizontalAlignment.Center,
  62. VerticalAlignment = VerticalAlignment.Center
  63. };
  64. return processingContext.DrawText(textOptions, text, color);
  65. }

示例效果

4、Chatbot

示例代码

  1. App.Launch(await CreateBlocks());
  2. ?
  3. async Task<Blocks> CreateBlocks()
  4. {
  5. using (var blocks = gr.Blocks())
  6. {
  7. gr.Markdown("# Chatbot Demo");
  8. ?
  9. var chatbot = gr.Chatbot();
  10. var msg = gr.Textbox(placeholder:"Enter to Submit");
  11. ?
  12. await msg.Submit(streamingFn: (input) => Respond(Textbox.Payload(input.Data[0]), Chatbot.Payload(input.Data[1])),
  13. inputs: new Component[] { msg, chatbot }, outputs: new Component[] { msg, chatbot });
  14. return blocks;
  15. }
  16. }
  17. ?
  18. static async IAsyncEnumerable<Output> Respond(string message, IList<ChatbotMessagePair> chatHistory)
  19. {
  20. chatHistory.Add(new ChatbotMessagePair(message, "You typed: "));
  21. ?
  22. for (int i = 0; i < message.Length; i++)
  23. {
  24. await Task.Delay(500);
  25. chatHistory.Last().AiMessage.TextMessage += message[i];
  26. ?
  27. yield return gr.Output("", chatHistory);
  28. }
  29. }

示例效果

5、Progress

根据自己的需求,调整进度条代码,参考代码如下:

  1. App.Launch(await CreateBlocks());
  2. ?
  3. async Task<Blocks> CreateBlocks()
  4. {
  5. using (var blocks = gr.Blocks())
  6. {
  7. gr.Markdown("# Progress Demo");
  8. ?
  9. var load = gr.Button("Load");
  10. var label = gr.Label(label: "Loader");
  11. load.Click(LoadSet, outputs: new[] { label });
  12. ?
  13. return blocks;
  14. }
  15. }
  16. static async Task<Output> LoadSet(Input input)
  17. {
  18. const int count = 24;
  19. input.Progress = gr.Progress(count);
  20. for (int i = 0; i < count; i++)
  21. {
  22. input.Progress.Report(i, desc: "Loading...");
  23. await Task.Delay(100);
  24. }
  25. return gr.Output("Loaded");
  26. }

示例效果

还有更多示例代码,可以查看官方文档进行学习。

Gradio.NET 应用

对于 AI 的爱好者来说,Gradio.NET 提供了一个绝佳的机会,通过访问 https://qwen.starworks.cc:88/,让他们能够与通义千问开源模型进行互动。

使用 Gradio.NET 打造你的 通义千问 AI 聊天机器人,具体如下图所示:

这个 Web 应用不仅用户体验流畅,还能够记住会话历史,轻松识别语义,这一切都得益于其背后的先进技术。

该项目已开源,源代码地址:https://github.com/sdcb/Sdcb.DashScope

具体代码讲解,可以查看源码。

项目地址

Github:https://github.com/feiyun0112/Gradio.Net

Demo:https://github.com/feiyun0112/Gradio.Net/blob/main/readme_files

AI聊天:https://github.com/sdcb/Sdcb.DashScope

总结

Gradio.NET 致力于成为 .NET 开发者 构建Web 应用的首选框架。它的设计理念是简化开发过程,让每个人都能轻松参与到 Web 应用的开发中来。

如果你对创建聊天机器人感兴趣,可以试试上面这个开源项目,结合 Gradio.NET 开发自己的AI聊天,有需要的朋友们可以参考学习。

最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。

也可以加入微信公众号[DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!

 

原文链接:https://www.cnblogs.com/1312mn/p/18370464

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号