运用AI搭建中间服务层(三)

CognitiveServices文件夹

在这个文件夹中,我们需要添加以下文件:

  • IVisionService.cs

  • 视觉服务 .cs

  • 视觉结果.cs

  • IEntitySearchService.cs

  • 实体搜索服务.cs

  • 实体结果.cs

  • 帮助程序.cs

IVisionService.cs - 访问影像服务的接口定义,需要依赖注入

 
using System.IO;
using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public interface IVisionService{Task<Landmark> RecognizeLandmarkAsync(Stream imgStream);Task<Celebrity> RecognizeCelebrityAsync(Stream imgStream);}
}VisionService.cs - 访问影像服务的逻辑代码using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public class VisionService : IVisionService{const string LandmarkEndpoint = "https://eastasia.api.cognitive.microsoft.com/vision/v2.0/models/landmarks/analyze";const string CelebrityEndpoint = "https://eastasia.api.cognitive.microsoft.com/vision/v2.0/models/celebrities/analyze";const string Key1 = "0e290876aed45d69f6fb97bb621f71";const string Key2 = "9799f09b87e4be6b2be132309b8e57";private readonly IHttpClientFactory httpClientFactory;public VisionService(IHttpClientFactory cf){this.httpClientFactory = cf;}public async Task<Landmark> RecognizeLandmarkAsync(Stream imgStream){VisionResult result = await this.MakePostRequest(LandmarkEndpoint, imgStream);if (result?.result?.landmarks?.Length > 0){return result?.result?.landmarks[0];}return null;}public async Task<Celebrity> RecognizeCelebrityAsync(Stream imgStream){VisionResult result = await this.MakePostRequest(CelebrityEndpoint, imgStream);if (result?.result?.celebrities?.Length > 0){return result?.result?.celebrities[0];}return null;}private async Task<VisionResult> MakePostRequest(string uri, Stream imageStream){try{using (HttpClient httpClient = httpClientFactory.CreateClient()){using (StreamContent streamContent = new StreamContent(imageStream)){streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");using (var request = new HttpRequestMessage(HttpMethod.Post, uri)){request.Content = streamContent;request.Headers.Add("Ocp-Apim-Subscription-Key", Key1);using (HttpResponseMessage response = await httpClient.SendAsync(request)){if (response.IsSuccessStatusCode){string resultString = await response.Content.ReadAsStringAsync();VisionResult result = JsonConvert.DeserializeObject<VisionResult>(resultString);return result;}else{}}}return null;}}}catch (Exception ex){return null;}}}
}
 

小提示:上面的代码中的Key1/Key2是不可用的,请用自己申请的Key和对应的Endpoint来代替。

VisionResult.cs – 认知服务返回的结果类,用于反序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public class VisionResult{public Result result { get; set; }public string requestId { get; set; }}public class Result{public Landmark[] landmarks { get; set; }public Celebrity[] celebrities { get; set; }}public class Landmark{public string name { get; set; }public double confidence { get; set; }}public class Celebrity{public virtual string name { get; set; }public virtual double confidence { get; set; }}
}

IEntitySearchService.cs – 访问实体搜索服务的接口定义,需要依赖注入

using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public interface IEntitySearchService{Task<string> SearchEntityAsync(string query);}
}

EntitySearchService.cs – 访问实体搜索服务的逻辑代码

using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public class EntitySearchService : IEntitySearchService{const string SearchEntityEndpoint = "https://api.cognitive.microsoft.com/bing/v7.0/entities?mkt=en-US&q=";const string Key1 = "a0be81df8ad449481492a11107645b";const string Key2 = "0803e4673824f9abb7487d8c3db6dd";private readonly IHttpClientFactory httpClientFactory;public EntitySearchService(IHttpClientFactory cf){this.httpClientFactory = cf;}public async Task<string> SearchEntityAsync(string query){using (HttpClient hc = this.httpClientFactory.CreateClient()){string uri = SearchEntityEndpoint + query;string jsonResult = await Helper.MakeGetRequest(hc, uri, Key1);Debug.Write(jsonResult);return jsonResult;}}}
}

小提示:上面的代码中的Key1/Key2是不可用的,请用自己申请的Key和对应的Endpoint来代替。

EntityResult.cs – 认知服务返回的结果类,用于反序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public class EntityResult{public string _type { get; set; }public Querycontext queryContext { get; set; }public Entities entities { get; set; }public Rankingresponse rankingResponse { get; set; }}public class Querycontext{public string originalQuery { get; set; }}public class Entities{public Value[] value { get; set; }}public class Value{public string id { get; set; }public Contractualrule[] contractualRules { get; set; }public string webSearchUrl { get; set; }public string name { get; set; }public string url { get; set; }public Image image { get; set; }public string description { get; set; }public Entitypresentationinfo entityPresentationInfo { get; set; }public string bingId { get; set; }}public class Image{public string name { get; set; }public string thumbnailUrl { get; set; }public Provider[] provider { get; set; }public string hostPageUrl { get; set; }public int width { get; set; }public int height { get; set; }public int sourceWidth { get; set; }public int sourceHeight { get; set; }}public class Provider{public string _type { get; set; }public string url { get; set; }}public class Entitypresentationinfo{public string entityScenario { get; set; }public string[] entityTypeHints { get; set; }}public class Contractualrule{public string _type { get; set; }public string targetPropertyName { get; set; }public bool mustBeCloseToContent { get; set; }public License license { get; set; }public string licenseNotice { get; set; }public string text { get; set; }public string url { get; set; }}public class License{public string name { get; set; }public string url { get; set; }}public class Rankingresponse{public Sidebar sidebar { get; set; }}public class Sidebar{public Item[] items { get; set; }}public class Item{public string answerType { get; set; }public int resultIndex { get; set; }public Value1 value { get; set; }}public class Value1{public string id { get; set; }}}

Helper.cs – 帮助函数

using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;namespace CognitiveMiddlewareService.CognitiveServices
{public class Helper{public static byte[] GetBuffer(IFormFile formFile){Stream stream = formFile.OpenReadStream();MemoryStream memoryStream = new MemoryStream();formFile.CopyTo(memoryStream);var buffer = memoryStream.GetBuffer();return buffer;}public static MemoryStream GetStream(byte[] buffer){if (buffer == null){return null;}return new MemoryStream(buffer, false);}public static async Task<string> MakeGetRequest(HttpClient httpClient, string uri, string key){try{using (var request = new HttpRequestMessage(HttpMethod.Get, uri)){request.Headers.Add("Ocp-Apim-Subscription-Key", key);using (HttpResponseMessage response = await httpClient.SendAsync(request)){if (response.IsSuccessStatusCode){string jsonResult = await response.Content.ReadAsStringAsync();return jsonResult;}}}return null;}catch (Exception ex){return null;}}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/615495.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

可拖拽表单比传统表单好在哪里?

随着行业的进步和发展&#xff0c;可拖拽表单的应用价值越来越高&#xff0c;在推动企业实现流程化办公和数字化转型的过程中发挥了重要价值和作用&#xff0c;是提质增效的办公利器&#xff0c;也是众多行业客户朋友理想的合作伙伴。那么&#xff0c;可拖拽表单的优势特点表单…

【MySQL】聚合函数与分组查询

聚合函数与分组查询 一、聚合函数1、常见的聚合函数2、实例 二、分组查询1、group by子句2、准备工作3、实例4、having 条件 一、聚合函数 说明&#xff1a;聚合函数用来计算一组数据的集合并返回单个值&#xff0c;通常用这些函数完成&#xff1a;个数的统计&#xff0c;某列…

Dubbo 框架揭秘:分布式架构的精髓与魔法【一】

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 Dubbo 框架揭秘&#xff1a;分布式架构的精髓与魔法【一】 前言Dubbo是什么Dubbo的核心概念整体设计 前言 在数字时代&#xff0c;分布式架构正成为应对大规模流量和复杂业务场景的标配。Dubbo&#…

vue项目使用typescript创建抽象类及其使用

如题&#xff0c;可以在vue项目使用typescript创建抽象类&#xff0c;然后使用这个抽象类。 通过TypeScript&#xff0c;可以在前端应用抽象类了。抽象类的好处&#xff0c;可以同时满足继承和多态&#xff0c;好处多多。以vue3为例&#xff1a; 1、创建抽象类 据说js类中&a…

监督学习 - XGBoost(eXtreme Gradient Boosting)

什么是机器学习 XGBoost&#xff08;eXtreme Gradient Boosting&#xff09;是一种梯度提升树算法&#xff0c;它在梯度提升框架的基础上引入了一些创新性的特性&#xff0c;以提高模型性能和训练速度。XGBoost在解决结构化数据的分类和回归问题上表现出色&#xff0c;成为许多…

Unity-游戏与帧

游戏的本质就是一个死循环 “游戏的本质就是一个死循环”这句话&#xff0c;其实是指游戏引擎的主循环。游戏引擎是游戏开发中最核心的部分&#xff0c;它负责处理玩家的输入、更新游戏状态、渲染画面等工作&#xff0c;而这些工作都是在一个不断重复的循环中完成的。 具体来…

【快刊录用】ABS一星,2区,仅2个月15天录用!

2023年12月30日-2024年1月5日 进展喜讯 经核实&#xff0c;由我处Unionpub学术推荐的论文中&#xff0c;新增2篇论文录用、3篇上线见刊、1篇数据库检索&#xff1a; 录用通知 FA20107 FA20181 — 见刊通知 FB20805 FA20269 FA20797 检索通知 FA20199 — — 计算机…

配网故障定位技术的发展与应用:保障电力供应安全稳定的重要支撑

在现代社会&#xff0c;电力供应安全稳定对于国家经济发展和民生福祉至关重要。然而&#xff0c;随着电网规模的不断扩大&#xff0c;配网故障问题也日益突出。为了确保电力供应的连续性和可靠性&#xff0c;人们不断探索和研发各种故障定位技术。本文将介绍一种基于行波测距技…

[Linux 进程(二)] Linux进程状态

文章目录 1、进程各状态的概念1.1 运行状态1.2 阻塞状态1.3 挂起状态 2、Linux进程状态2.1 运行状态 R2.2 睡眠状态 S2.3 深度睡眠 D2.4 停止状态 T2.5 僵尸状态 Z 与 死亡状态 X孤儿进程 Linux内核中&#xff0c;进程状态&#xff0c;就是PCB中的一个字段&#xff0c;是PCB中的…

2401d,ddip1027如何支持sql

原文 以下是DIP1036的SQL支持方式: 这里 auto execi(Args...)(Sqlite db, InterpolationHeader header, Args args, InterpolationFooter footer) {import arsd.sqlite;//SQLite允许你执行?1,?2等操作enum string query () {string sql;int number;import std.conv;foreach…

智慧食堂管理方式,究竟改变了什么?

随着科技的迅速发展&#xff0c;餐饮业也在不断地迎来新的挑战和机遇。为了提升食堂管理效率、改善用户体验以及提高收益&#xff0c;许多食堂纷纷引入智慧收银系统。 客户案例 企业食堂改革 石家庄某大型企业食堂由于员工数量庞大&#xff0c;传统的收银方式难以满足快速就餐…

大话 JavaScript(Speaking JavaScript):第二十一章到第二十五章

第二十一章&#xff1a;数学 原文&#xff1a;21. Math 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 Math对象用作多个数学函数的命名空间。本章提供了一个概述。 数学属性 Math的属性如下&#xff1a; Math.E 欧拉常数&#xff08;e&#xff09; Math.LN2 2 …

Verilog 和 System Verilog 的区别

当谈到VLSI设计和数字电路建模时&#xff0c;verilog和system verilog是两种常用的硬件描述语言。这些 HDL 在 VLSI 设计中用于描述电子电路的行为和结构。它们都广泛应用于半导体行业来设计和实现集成电路&#xff08;IC&#xff09;。 它们是设计和模拟复杂数字系统的强大工具…

解决:ModuleNotFoundError: No module named ‘dbutils’

解决&#xff1a;ModuleNotFoundError: No module named ‘dbutils’ 文章目录 解决&#xff1a;ModuleNotFoundError: No module named dbutils背景报错问题报错翻译报错位置代码报错原因解决方法方法一&#xff0c;直接安装方法二&#xff0c;手动下载安装方法三&#xff0c;…

盈利之道:下单前的必问之问

投资者在过去的交易经历中&#xff0c;通常都会面临所谓的“交易低谷”。交易低谷是指在交易过程中难以实现盈利或可能导致进一步亏损的阶段。这种面临损失或没有盈利的时期可能发生在任何人身上&#xff0c;无论是由于市场变化、投资者策略调整还是其他原因。为了应对这种情况…

C++力扣题目--94,144,145二叉树递归遍历

思路 这次我们要好好谈一谈递归&#xff0c;为什么很多同学看递归算法都是“一看就会&#xff0c;一写就废”。 主要是对递归不成体系&#xff0c;没有方法论&#xff0c;每次写递归算法 &#xff0c;都是靠玄学来写代码&#xff0c;代码能不能编过都靠运气。 本篇将介绍前后…

Hibernate实战之操作MySQL数据库(2024-1-8)

Hibernate实战之操作MySQL数据库 2024.1.8 前提环境&#xff08;JavaMySQLNavicatVS Code&#xff09;1、Hibernate简介1.1 了解HQL 2、MySQL数据库建表2.1 编写SQL脚本2.2 MySQL执行脚本 3、Java操作MySQL实例&#xff08;Hibernate&#xff09;3.1 准备依赖的第三方jar包3.2 …

Mybatis自动加解密

涉及隐私信息的字段需要加密存储数据库&#xff0c;返回给前端时又需要解密显示正确信息。故采用mybatis自动加解密的方案&#xff0c;该方案基于自定义注解拦截器进行实现。加密后的信息不支持模糊匹配&#xff08;可参考业界流行方案&#xff0c;基于业务需求做分词或采用其他…

与听力学相关的职业都有哪些?怎么选择?

随着年龄的增长&#xff0c;每个人都可能面临听觉障碍的困惑。听力学领域专注于患者的耳朵问题&#xff0c;包括听力损失和平衡障碍。听力学职业是为患者提供听觉健康管理服务的职业&#xff0c;专注于他们耳朵的听力和平衡甚至言语相关需求。为患者进行听功能检查、测试、诊疗…

1.5如何用命令得到自己的ip<本地>

专栏导航 第四章 具有通用性的花生壳ddns脚本 第五章 如何用命令得到自己的ip<本地> ⇐ 第六章 用命令得到ip和域名解析<网络>() 用折腾路由的兴趣,顺便入门shell编程。 第五章 如何用命令得到ip<本地> 文章目录 专栏导航第五章 如何用命令得到ip<本地…