百度人脸识别

This commit is contained in:
李超 2025-07-27 20:02:25 +08:00
parent 3df2c98c67
commit c93709974b
20 changed files with 1481 additions and 0 deletions

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class APIBaseModel<T> where T : class, new()
{
public T contextModel//这里的context 调用要重新实例化一个
{
get; set;
}
public bool state { get; set; }
/// <summary>
/// 非接口信息错误
/// </summary>
public string errorMsg { get; set; }
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class AccessTokenModel
{
public bool IsSuccess { get; set; }
public SuccessAccessTokenModel SuccessModel { get; set; }
public ErrorAccessTokenModel ErrorModel { get; set; }
}
/// <summary>
/// 获取accesstoken正常 的 百度接口返回的json 实体模型
/// </summary>
public class SuccessAccessTokenModel
{
public string refresh_token { get; set; }
public int expires_in { get; set; }
public string scope { get; set; }
public string session_key { get; set; }
public string session_secret { get; set; }
public string access_token { get; set; }
}
/// <summary>
/// 获取accesstoken失败的 百度接口返回的json 实体模型
/// </summary>
public class ErrorAccessTokenModel
{
public string error { get; set; }
public string error_description { get; set; }
}
}

View File

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class BaiduError
{
public static string getBaiduError(String errCode)
{
string error = "未知错误";
switch (errCode)
{
case "222202":
error = "未识别到人脸";
break;
case "223106":
error = "该人脸不存在";
break;
case "223110":
error = "uid_list包含数量过多";
break;
case "223111":
error = "目标用户组不存在";
break;
case "223112":
error = "quality_conf格式不正确";
break;
case "223113":
error = "人脸有被遮挡,请重新操作";
break;
case "223114":
error = "人脸模糊,请重新操作";
break;
case "223115":
error = "人脸光照不好,请重新操作";
break;
case "223116":
error = "人脸不完整,请重新操作";
break;
case "223117":
error = "app_list包含app数量过多";
break;
case "223118":
error = "质量控制项错误";
break;
case "223119":
error = "活体控制项错误";
break;
case "223120":
error = "活体检测未通过,请重新操作";
break;
case "223121":
error = "左眼遮挡程度过高,请重新操作";
break;
case "223122":
error = "右眼遮挡程度过高,请重新操作";
break;
case "223123":
error = "左脸遮挡程度过高,请重新操作";
break;
case "223124":
error = "右脸遮挡程度过高,请重新操作";
break;
case "223125":
error = "下巴遮挡程度过高,请重新操作";
break;
case "223126":
error = "鼻子遮挡程度过高,请重新操作";
break;
case "223127":
error = "嘴巴遮挡程度过高,请重新操作";
break;
}
return error;
}
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class ConfigAppSetting
{
public static double getConfigAppSetting(String name)
{
try
{
return Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings[name]);
}
catch (Exception ex)
{
return 0;
}
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
/// <summary>
/// 错误信息 实体
/// </summary>
public class ErrorTypeModel
{
/// <summary>
/// 日志Id
/// </summary>
public string log_id { get; set; }
/// <summary>
/// 错误码
/// </summary>
public string error_code { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string error_msg { get; set; }
/// <summary>
/// 错误信息中文描述
/// </summary>
public string error_discription { get; set; }
}
}

View File

@ -0,0 +1,312 @@
using AOP.Common.DataConversion;
using Baidu.Aip.Face;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public static class FaceClass
{
public static Baidu.Aip.Face.Face getFaceClant()
{
// 设置APPID/AK/SK
var APP_ID = System.Configuration.ConfigurationManager.AppSettings["APP_ID"].ToString();
var API_KEY = System.Configuration.ConfigurationManager.AppSettings["API_KEY"].ToString();
var SECRET_KEY = System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString();
var client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
return client;
}
public static object SearchFileFace(String imagePath)
{
String strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg); // 图片的base64编码
var imageType = "BASE64";
var groupIdList = "WX_Face_TCC";
// 如果有可选参数
var options = new Dictionary<string, object>{
{"quality_control", "NORMAL"},
{"liveness_control", "NORMAL"},
{"max_user_num", 1}
};
// 带参数调用人脸搜索
object result = new object();
List<faceResult> frs = new List<faceResult>();
try
{
result = getFaceClant().Search(strbaser64, imageType, groupIdList, options);
if (result != null)
{
var data = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result));
String error_msg = data.error_msg;
String errorCode = data.error_code;
if (error_msg == "SUCCESS")
{
for (int i = 0; i < data.result.user_list.Count; i++)
{
faceResult fr = new faceResult();
fr.user_id = data.result.user_list[i].user_id;
fr.user_info = getUserName(fr.user_id);
fr.errMess = error_msg;
try
{
string score = data.result.user_list[i].score.ToString();
fr.score = double.Parse(score);
}
catch
{
fr.score = 0;
}
if (fr.score > 85)
frs.Add(fr);
}
}
else
{
faceResult fr = new faceResult();
fr.errMess = error_msg;
fr.errCode = errorCode;
frs.Add(fr);
}
}
}
catch (Exception ex)
{
faceResult fr = new faceResult();
fr.errMess = ex.ToString();
frs.Add(fr);
}
return frs;
}
public static object SearchFace(String url)
{
var image = url;
var imageType = "URL";
var groupIdList = "WX_Face_TCC";
// 如果有可选参数
var options = new Dictionary<string, object>{
{"quality_control", "NORMAL"},
{"liveness_control", "LOW"},
{"max_user_num", 1}
};
// 带参数调用人脸搜索
object result = new object();
try
{
result = getFaceClant().Search(image, imageType, groupIdList, options);
}
catch (Exception ex)
{
return null;
}
List<faceResult> frs = new List<faceResult>();
if (result != null)
{
var data = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result));
String error_msg = data.error_msg;
if (error_msg == "SUCCESS")
{
for (int i = 0; i < data.result.user_list.Count; i++)
{
faceResult fr = new faceResult();
fr.user_id = data.result.user_list[i].user_id;
fr.user_info = getUserName(fr.user_id);
try
{
string score = data.result.user_list[i].score.ToString();
fr.score = double.Parse(score);
}
catch
{
fr.score = 0;
}
if (fr.score > 85)
{
frs.Add(fr);
break;
}
}
}
else return null;
}
return frs;
}
public static String getUserName(string id)
{
string userName = "未知用户";
switch (id)
{
case "A01844":
userName = "张腾云";
break;
case "A04979":
userName = "张延强";
break;
case "A05352":
userName = "王勇C";
break;
case "A06539":
userName = "崔璐峰";
break;
case "A04984":
userName = "杨新民";
break;
case "A05303":
userName = "李文娟";
break;
case "A04988":
userName = "马明";
break;
case "A06926":
userName = "王建峰";
break;
default:
userName = "未知用户";
break;
}
return userName;
}
// 在线活体检测
public static string FaceVerify(string imagePath)
{
string token = AccessToken.getAccessToken();
string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify?access_token=" + token;
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.KeepAlive = true;
String strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg); // 图片的base64编码
String str = "[{\"image\":\"" + strbaser64 + "\",\"image_type\":\"BASE64\",\"face_field\":\"quality,human\"}]";
byte[] buffer = encoding.GetBytes(str);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string result = reader.ReadToEnd();
//Console.WriteLine("在线活体检测:");
Console.WriteLine(result);
return result;
}
// 人脸注册
public static string add(string user_id, string user_card, string imgUrl, string token)
{
bool first = true;
if (string.IsNullOrEmpty(token))
{
token = AccessToken.getAccessToken();
first = false;
}
string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + token;
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.KeepAlive = true;
String str = "{\"image\":\"" + imgUrl + "\",\"image_type\":\"URL\",\"group_id\":\"WX_Face_TCC\",\"user_id\":\"" + user_card + "\",\"user_info\":\"" + user_id + "\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
byte[] buffer = encoding.GetBytes(str);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string result = reader.ReadToEnd();
//Console.WriteLine("人脸注册:");
//Console.WriteLine(result);
var res = JsonConvert.DeserializeObject<dynamic>(result);
if (result.Contains("Access token invalid or no longer valid") && first)
{
token = null;
add(user_id, user_card, imgUrl, token);
}
if (result.Contains("face is already exist"))
result = update(user_id, user_card, imgUrl, token);
if (res.error_code == "0")
{
}
return result;
}
// 人脸更新
public static string update(string user_id, string user_card, string imgUrl, string token)
{
if (string.IsNullOrEmpty(token))
token = AccessToken.getAccessToken();
string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update?access_token=" + token;
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.KeepAlive = true;
String str = "{\"image\":\"" + imgUrl + "\",\"image_type\":\"URL\",\"group_id\":\"WX_Face_TCC\",\"user_id\":\"" + user_card + "\",\"user_info\":\"" + user_id + "\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
byte[] buffer = encoding.GetBytes(str);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string result = reader.ReadToEnd();
if (result.Contains("user is not exist"))
result = add(user_id, user_card, imgUrl, token);
return result;
}
}
public static class AccessToken
{
// 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
// 返回token示例
public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";
// 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
private static String clientId = "百度云应用的AK";
// 百度云中开通对应服务应用的 Secret Key
private static String clientSecret = "百度云应用的SK";
public static String getAccessToken()
{
String authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client = new HttpClient();
List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", System.Configuration.ConfigurationManager.AppSettings["API_KEY"].ToString()));
paraList.Add(new KeyValuePair<string, string>("client_secret", System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString()));
HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
String result = response.Content.ReadAsStringAsync().Result;
var to = JsonConvert.DeserializeObject<dynamic>(result);
Console.WriteLine(result);
return to.access_token;
}
}
}

View File

@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class Gpslocation
{
public double lat;
public double lng;
}
public class GpsPolygonHelper
{/// <summary>
/// 判断当前位置是否在不规则形状里面
/// </summary>
/// <param name="nvert">不规则形状的定点数</param>
/// <param name="vertx">当前x坐标</param>
/// <param name="verty">当前y坐标</param>
/// <param name="testx">不规则形状x坐标集合</param>
/// <param name="testy">不规则形状y坐标集合</param>
/// <returns></returns>
public static bool PositionPnpoly(int nvert, List<double> vertx, List<double> verty, double testx, double testy)
{
int i, j, c = 0;
for (i = 0, j = nvert - 1; i < nvert; j = i++)
{
if (((verty[i] > testy) != (verty[j] > testy)) && (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))
{
c = 1 + c; ;
}
}
if (c % 2 == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 坐标点是否在多边形内判断
/// </summary>
/// <param name="point"></param>
/// <param name="pts"></param>
/// <returns></returns>
public static bool isPointInPolygon(Gpslocation point, List<Gpslocation> pts)
{
//检查类型
if (point == null || pts == null)
return false;
var N = pts.Count;
var boundOrVertex = true; //如果点位于多边形的顶点或边上也算做点在多边形内直接返回true
var intersectCount = 0; //cross points count of x
var precision = 2e-10; //浮点类型计算时候与0比较时候的容差
Gpslocation p1, p2; //neighbour bound vertices
var p = point; //测试点
p1 = pts[0]; //left vertex
for (var i = 1; i <= N; ++i)
{
//check all rays
if (p.lat.Equals(p1.lat) && p.lng.Equals(p1.lng))
{
return boundOrVertex; //p is an vertex
}
p2 = pts[i % N]; //right vertex
if (p.lat < Math.Min(p1.lat, p2.lat) || p.lat > Math.Max(p1.lat, p2.lat))
{
//ray is outside of our interests
p1 = p2;
continue; //next ray left point
}
if (p.lat > Math.Min(p1.lat, p2.lat) && p.lat < Math.Max(p1.lat, p2.lat))
{
//ray is crossing over by the algorithm (common part of)
if (p.lng <= Math.Max(p1.lng, p2.lng))
{
//x is before of ray
if (p1.lat == p2.lat && p.lng >= Math.Min(p1.lng, p2.lng))
{
//overlies on a horizontal ray
return boundOrVertex;
}
if (p1.lng == p2.lng)
{
//ray is vertical
if (p1.lng == p.lng)
{
//overlies on a vertical ray
return boundOrVertex;
}
else
{
//before ray
++intersectCount;
}
}
else
{
//cross point on the left side
var xinters =
(p.lat - p1.lat) * (p2.lng - p1.lng) / (p2.lat - p1.lat) +
p1.lng; //cross point of lng
if (Math.Abs(p.lng - xinters) < precision)
{
//overlies on a ray
return boundOrVertex;
}
if (p.lng < xinters)
{
//before ray
++intersectCount;
}
}
}
}
else
{
//special case when ray is crossing through the vertex
if (p.lat == p2.lat && p.lng <= p2.lng)
{
//p crossing over p2
var p3 = pts[(i + 1) % N]; //next vertex
if (p.lat >= Math.Min(p1.lat, p3.lat) && p.lat <= Math.Max(p1.lat, p3.lat))
{
//p.lat lies between p1.lat & p3.lat
++intersectCount;
}
else
{
intersectCount += 2;
}
}
}
p1 = p2; //next ray left point
}
if (intersectCount % 2 == 0)
{
//偶数在多边形外
return false;
}
else
{
//奇数在多边形内
return true;
}
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class IDCardClass
{
// Distinguish(pb_SidePic.ImageLocation, "back", false, "true");
// Distinguish(pb_PositivePic.ImageLocation, "front", false, "true");
/// <summary>
/// 识别操作
/// </summary>
/// <param name="filePath"></param>
/// <param name="id_card_side">身份证 正面还是背面</param>
/// <param name="detect_direction"></param>
/// <param name="detect_risk"></param>
public static APIBaseModel<IDCardRecognitionModel> idcard(string filePath, string id_card_side = "front", bool detect_direction = false, string detect_risk = "false")
{
var temp = IDCardToken.GetAccessToken();
if (temp.IsSuccess)
{
string data = "";
string error = "";
string token = temp.SuccessModel.access_token;
var result = IDCardRecognition.GetIdcardRecognitionString(temp.SuccessModel.access_token, filePath, ref data, out error, id_card_side, detect_direction, detect_risk);
return result;
}
return null;
}
}
}

View File

@ -0,0 +1,84 @@
using AOP.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace SgManager.AI
{
/// <summary>
/// 文字识别--身份证识别 应用(只是获取身份证图片 信息,没有和公安部联网,无法确认真假,只是单纯从图片上识别文字)
/// </summary>
public class IDCardRecognition
{
// 身份证识别
/// <summary>
/// 身份证识别
/// </summary>
/// <param name="token">Accesstoken</param>
/// <param name="imagePath">图片路径</param>
/// <param name="recognitionString">识别结果</param>
/// <param name="errorMsg">错误信息</param>
/// <param name="id_card_side"> front身份证正面back身份证背面</param>
/// <param name="detect_direction">是否检测图像朝向默认不检测false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:- true检测朝向- false不检测朝向。</param>
/// <param name="detect_risk"> string 类型 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能默认不开启false。可选值:true-开启false-不开启</param>
/// <returns>结果状态</returns>
public static APIBaseModel<IDCardRecognitionModel> GetIdcardRecognitionString(string token, string imagePath, ref string recognitionString, out string errorMsg, string id_card_side = "front", bool detect_direction = false, string detect_risk = "false")
{
bool resultState = true;
APIBaseModel<IDCardRecognitionModel> tempModel = new APIBaseModel<IDCardRecognitionModel>();
tempModel.contextModel = new IDCardRecognitionModel();
string strbaser64 = "";
try
{
#region
string verificationMsg = "";
errorMsg = "";
var verifyResult = ImageVerification.VerificationImage<IDCardRecognitionModel>(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg, tempModel, out verificationMsg, out strbaser64);
if (!verifyResult.state)
{
return verifyResult;
}
recognitionString = "";
string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token;
String str = "id_card_side=" + id_card_side + "&detect_direction=" + detect_direction + "&detect_risk=" + detect_risk + "&image=" + HttpUtility.UrlEncode(strbaser64);
var tempResult = HttpRequestHelper.Post(host, str);
recognitionString = tempResult;
if (recognitionString.Contains("\"error_code\""))//说明异常
{
resultState = false;
tempModel.state = false;
tempModel.contextModel.errorTypeModel = Json.ToObject<ErrorTypeModel>(tempResult);
tempModel.contextModel.errorTypeModel.error_discription = OCR_CharacterRecognitionErrorType.GetErrorCodeToDescription(tempModel.contextModel.errorTypeModel.error_code);
}
else
{
tempModel.state = true;
var temp = Json.ToObject<IDCardRecognitionSuccessResultModel>(tempResult);
tempModel.contextModel.successModel = temp;
}
#endregion
return tempModel;
}
catch (Exception ex)//接口外部异常,如网络异常
{
resultState = false;
errorMsg = ex.ToString();
tempModel.state = false;
tempModel.errorMsg = ex.ToString();
return tempModel;
}
}
}
}

View File

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{ /// <summary>
/// 身份证识别 实体
/// </summary>
public class IDCardRecognitionModel
{
public IDCardRecognitionSuccessResultModel successModel { get; set; }
public ErrorTypeModel errorTypeModel { get; set; }
}
public class IDCardRecognitionSuccessResultModel
{
public long log_id { get; set; }
public int direction { get; set; }
public int words_result_num { get; set; }
public string image_status { get; set; }
public string idcard_type { get; set; }
public string edit_tool { get; set; }
public string risk_type { get; set; }
public Words_result words_result { get; set; }
}
public class Words_result
{
public { get; set; }
public { get; set; }
public { get; set; }
public { get; set; }
public { get; set; }
public { get; set; }
public { get; set; }
public { get; set; }
public { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class
{
public Location location { get; set; }
public string words { get; set; }
}
public class Location
{
public int left { get; set; }
public int top { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class DicModel
{
public string words { get; set; }
public Location location { get; set; }
}
}

View File

@ -0,0 +1,60 @@
using AOP.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public static class IDCardToken
{
// 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
// 返回token示例
public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";
// 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
private static String clientId = System.Configuration.ConfigurationManager.AppSettings["ID_API_KEY"].ToString();// "onreA4ms0OUi2eclj8CnMoaV";
// 百度云中开通对应服务应用的 Secret Key
private static String clientSecret = System.Configuration.ConfigurationManager.AppSettings["ID_SECRET_KEY"].ToString();// "ge8kERfb5uxqUKyOhdLMD2ozumNUigjY";
private static String getBaiduAccessToken()
{
String authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client = new HttpClient();
List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
String result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
return result;
}
public static AccessTokenModel GetAccessToken()
{
AccessTokenModel tempAccessTokenModel = new AccessTokenModel();
string tempData = getBaiduAccessToken();
if (tempData.Contains("\"error\""))
{//标识异常
tempAccessTokenModel.IsSuccess = false;
tempAccessTokenModel.ErrorModel = Json.ToObject<ErrorAccessTokenModel>(tempData);
}
else
{//标识正常
tempAccessTokenModel.IsSuccess = true;
tempAccessTokenModel.SuccessModel = Json.ToObject<SuccessAccessTokenModel>(tempData);
}
return tempAccessTokenModel;
}
}
}

View File

@ -0,0 +1,142 @@
using AOP.Common.DataConversion;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace SgManager.AI
{
public class ImageVerification
{
/// <summary>
/// 验证图片规格
/// </summary>
/// <param name="filePath">图片路径</param>
/// <param name="Msg"></param>
/// <param name="defaultImageSize">默认图片最大是4MB</param>
/// <param name="defaultShortLength">默认最短15px</param>
/// <param name="defaultLongLength">默认最长4096px</param>
/// <returns>是否验证通过</returns>
public static bool VerificationImage(string filePath, out string Msg, int defaultImageSize = 1024 * 1024 * 4, int defaultShortLength = 15, int defaultLongLength = 4096)
{
bool isPass = true;
Msg = "";//提示信息
string filename = System.IO.Path.GetFileName(filePath);
#region
if (!File.Exists(filePath))
{
return false;
}
if (string.IsNullOrEmpty(filename))
{
Msg = "文件不能为空!";
return false;
}
#endregion
#region
bool isImg = false;//是否是图片标识
string[] imgTypeList = new string[] { ".jpg", ".png", "bmp" };
//得到文件后缀
string fileType = System.IO.Path.GetExtension(filePath);
for (int i = 0; i < imgTypeList.Count(); i++)
{
if (fileType.ToLower() == imgTypeList[i])
{
isImg = true;
}
}
if (!isImg)
{
Msg = "上传文件不是图片格式!请重新上传!";
return false;
}
#endregion
#region
int imgSize = defaultImageSize;
byte[] bs = File.ReadAllBytes(filePath);
if (bs.Length > imgSize)
{
Msg = "图片大小不能" + imgSize / 1024 / 1024 + "MB";
return false;
}
#endregion
#region
System.Drawing.Image tempImage = System.Drawing.Image.FromFile(filePath);
int picWidth = tempImage.Width;
int picHeigth = tempImage.Height;
if (!(defaultShortLength <= picWidth && picWidth <= defaultLongLength) && (defaultShortLength <= picHeigth && picHeigth <= defaultLongLength))
{
Msg = "图片尺寸规格最短边至少" + defaultShortLength + "px最长边最大" + defaultLongLength + "px,";
return false;
}
#endregion
return isPass;
}
public static APIBaseModel<T> VerificationImage<T>(string imagePath, System.Drawing.Imaging.ImageFormat imageFormat, APIBaseModel<T> tempModel, out string errorMsg, out string strbaser64) where T : class, new()
{
#region
string verificationMsg = "";
strbaser64 = "";
errorMsg = "";
bool isVerification = ImageVerification.VerificationImage(imagePath, out verificationMsg);
if (!isVerification)
{
errorMsg += verificationMsg;
tempModel.state = false;
tempModel.errorMsg = errorMsg;
return tempModel;
}
strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, imageFormat); // 图片的base64编码
Encoding encoding = Encoding.Default;
string urlEncodeImage = HttpUtility.UrlEncode(strbaser64);
byte[] tempBuffer = encoding.GetBytes(urlEncodeImage);
if (tempBuffer.Length > 1024 * 1024 * 4)
{
errorMsg += "图片加密 后的大小超过4MB";
tempModel.state = false;
tempModel.errorMsg = errorMsg;
return tempModel;
}
tempModel.state = true;
return tempModel;
#endregion
}
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
class MapClass
{
}
}

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class OCR_CharacterRecognitionErrorType
{
public static string GetErrorCodeToDescription(string errorCode)
{
string errorDecrition = "";
switch (errorCode)
{
case "1": errorDecrition = "服务器内部错误,请再次请求, 如果持续出现此类错误请通过QQ群224994340或工单联系技术支持团队。"; break;
case "2": errorDecrition = "服务暂不可用,请再次请求, 如果持续出现此类错误请通过QQ群224994340或工单联系技术支持团队。"; break;
case "3": errorDecrition = "调用的API不存在请检查后重新尝试。"; break;
case "4": errorDecrition = "集群超限额。"; break;
case "6": errorDecrition = "无权限访问该用户数据。"; break;
case "14": errorDecrition = "IAM鉴权失败建议用户参照文档自查生成sign的方式是否正确或换用控制台中ak sk的方式调用。"; break;
case "17": errorDecrition = "每天请求量超限额。"; break;
case "18": errorDecrition = "QPS超限额。"; break;
case "19": errorDecrition = "请求总量超限额。"; break;
case "100": errorDecrition = "无效的access_token参数请检查后重新尝试。"; break;
case "110": errorDecrition = "access token过期。"; break;
case "282000": errorDecrition = "服务器内部错误,如果您使用的是高精度接口,报这个错误码的原因可能是您上传的图片中文字过多,识别超时导致的,建议您对图片进行切割后再识别,其他情况请再次请求, 如果持续出现此类错误请通过QQ群631977213或工单联系技术支持团队。"; break;
case "216100": errorDecrition = "请求中包含非法参数,请检查后重新尝试。"; break;
case "216101": errorDecrition = "缺少必须的参数,请检查参数是否有遗漏。"; break;
case "216102": errorDecrition = "请求了不支持的服务请检查调用的url。"; break;
case "216103": errorDecrition = "请求中某些参数过长,请检查后重新尝试。"; break;
case "216110": errorDecrition = "appid不存在请重新核对信息是否为后台应用列表中的appid。"; break;
case "216200": errorDecrition = "图片为空,请检查后重新尝试。"; break;
case "216201": errorDecrition = "上传的图片格式错误现阶段我们支持的图片格式为PNG、JPG、JPEG、BMP请进行转码或更换图片。"; break;
case "216202": errorDecrition = "上传的图片大小错误现阶段我们支持的图片大小为base64编码后小于4M分辨率不高于4096*4096请重新上传图片。"; break;
case "216630": errorDecrition = "识别错误请再次请求如果持续出现此类错误请通过QQ群631977213或工单联系技术支持团队。"; break;
case "216631": errorDecrition = "识别银行卡错误,出现此问题的原因一般为:您上传的图片非银行卡正面,上传了异形卡的图片或上传的银行卡正品图片不完整。"; break;
case "216633": errorDecrition = "识别身份证错误,出现此问题的原因一般为:您上传了非身份证图片或您上传的身份证图片不完整。"; break;
case "216634": errorDecrition = "检测错误请再次请求如果持续出现此类错误请通过QQ群631977213或工单联系技术支持团队。"; break;
case "282003": errorDecrition = "请求参数缺失。"; break;
case "282005": errorDecrition = "处理批量任务时发生部分或全部错误,请根据具体错误码排查。"; break;
case "282006": errorDecrition = "批量任务处理数量超出限制请将任务数量减少到10或10以下。"; break;
case "282110": errorDecrition = "URL参数不存在请核对URL后再次提交。"; break;
case "282111": errorDecrition = "URL格式非法请检查url格式是否符合相应接口的入参要求。"; break;
case "282112": errorDecrition = "url下载超时请检查url对应的图床/图片无法下载或链路状况不好,您可以重新尝试一下,如果多次尝试后仍不行,建议更换图片地址。"; break;
case "282113": errorDecrition = "URL返回无效参数。"; break;
case "282114": errorDecrition = "URL长度超过1024字节或为0。"; break;
case "282808": errorDecrition = "request id xxxxx 不存在。"; break;
case "282809": errorDecrition = "返回结果请求错误不属于excel或json。"; break;
case "282810": errorDecrition = "图像识别错误。"; break;
default: errorDecrition = "未知的错误!"; break;
}
return errorDecrition;
}
}
}

View File

@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class PostMail
{
public class EmailParameterSet
{
/// <summary>
/// 收件人的邮件地址
/// </summary>
public string ConsigneeAddress { get; set; }
/// <summary>
/// 收件人的名称
/// </summary>
public string ConsigneeName { get; set; }
/// <summary>
/// 收件人标题
/// </summary>
public string ConsigneeHand { get; set; }
/// <summary>
/// 收件人的主题
/// </summary>
public string ConsigneeTheme { get; set; }
/// <summary>
/// 发件邮件服务器的Smtp设置
/// </summary>
public string SendSetSmtp { get; set; }
/// <summary>
/// 发件人的邮件
/// </summary>
public string SendEmail { get; set; }
/// <summary>
/// 发件人的邮件密码
/// </summary>
public string SendPwd { get; set; }
/// <summary>
/// 发件内容
/// </summary>
public string SendContent { get; set; }
}
public bool MailSend(EmailParameterSet EPSModel)
{
try
{
//确定smtp服务器端的地址实列化一个客户端smtp
System.Net.Mail.SmtpClient sendSmtpClient = new System.Net.Mail.SmtpClient(EPSModel.SendSetSmtp);//发件人的邮件服务器地址
//构造一个发件的人的地址
System.Net.Mail.MailAddress sendMailAddress = new MailAddress(EPSModel.SendEmail, EPSModel.ConsigneeHand, Encoding.UTF8);//发件人的邮件地址和收件人的标题、编码
//构造一个收件的人的地址
System.Net.Mail.MailAddress consigneeMailAddress = new MailAddress(EPSModel.ConsigneeAddress, EPSModel.ConsigneeName, Encoding.UTF8);//收件人的邮件地址和收件人的名称 和编码
//构造一个Email对象
System.Net.Mail.MailMessage mailMessage = new MailMessage(sendMailAddress, consigneeMailAddress);//发件地址和收件地址
mailMessage.Subject = EPSModel.ConsigneeTheme;//邮件的主题
mailMessage.BodyEncoding = Encoding.UTF8;//编码
mailMessage.SubjectEncoding = Encoding.UTF8;//编码
mailMessage.Body = EPSModel.SendContent;//发件内容
mailMessage.IsBodyHtml = false;//获取或者设置指定邮件正文是否为html
//设置邮件信息 (指定如何处理待发的电子邮件)
sendSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定如何发邮件 是以网络来发
sendSmtpClient.EnableSsl = false;//服务器支持安全接连安全则为true
sendSmtpClient.UseDefaultCredentials = false;//是否随着请求一起发
//用户登录信息
NetworkCredential myCredential = new NetworkCredential(EPSModel.SendEmail, EPSModel.SendPwd);
sendSmtpClient.Credentials = myCredential;//登录
sendSmtpClient.Send(mailMessage);//发邮件
return true;//发送成功
}
catch (Exception)
{
return false;//发送失败
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("SgManager.AI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SgManager.AI")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("55f4e1e2-5fb3-4ab4-b692-432ce41b3e61")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{55F4E1E2-5FB3-4AB4-B692-432CE41B3E61}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SgManager.AI</RootNamespace>
<AssemblyName>SgManager.AI</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="AipSdk, Version=3.5.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\FineUIPro\Reference BLL\AipSdk.dll</HintPath>
</Reference>
<Reference Include="AOP.Common">
<HintPath>..\FineUIPro\Reference BLL\AOP.Common.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AccessTokenModel.cs" />
<Compile Include="APIBaseModel.cs" />
<Compile Include="BaiduError.cs" />
<Compile Include="ConfigAppSetting.cs" />
<Compile Include="ErrorTypeModel.cs" />
<Compile Include="FaceClass.cs" />
<Compile Include="faceResult.cs" />
<Compile Include="GpsPolygonHelper.cs" />
<Compile Include="IDCardRecognition.cs" />
<Compile Include="IDCardRecognitionModel.cs" />
<Compile Include="IDCardClass.cs" />
<Compile Include="IDCardToken.cs" />
<Compile Include="ImageVerification.cs" />
<Compile Include="MapClass.cs" />
<Compile Include="OCR_CharacterRecognitionErrorType.cs" />
<Compile Include="PostMail.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SgManager.AI
{
public class faceResult
{
public String errMess { get; set; }
public String user_id { get; set; }
public String user_info { get; set; }
public String errCode { get; set; }
public double score { get; set;}
}
}

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net45" />
</packages>