Compare commits

...

8 Commits

28 changed files with 2016 additions and 34 deletions

View File

@ -1336,6 +1336,7 @@
<Content Include="WeldMat\UsingPlan\UsingPlanImport.aspx" />
<Content Include="WeldMat\UsingPlan\UsingPlanImport2.aspx" />
<Content Include="WeldMat\UsingSentMat\CodeConfirm.aspx" />
<Content Include="WeldMat\UsingSentMat\FaceRecognition.aspx" />
<Content Include="WeldMat\UsingSentMat\LC700.aspx" />
<Content Include="WeldMat\UsingSentMat\ModityWeld.aspx" />
<Content Include="WeldMat\UsingSentMat\ShowReturnMat.aspx" />
@ -6962,6 +6963,13 @@
<Compile Include="WeldMat\UsingSentMat\CodeConfirm.aspx.designer.cs">
<DependentUpon>CodeConfirm.aspx</DependentUpon>
</Compile>
<Compile Include="WeldMat\UsingSentMat\FaceRecognition.aspx.cs">
<DependentUpon>FaceRecognition.aspx</DependentUpon>
<SubType>ASPXCodeBehind</SubType>
</Compile>
<Compile Include="WeldMat\UsingSentMat\FaceRecognition.aspx.designer.cs">
<DependentUpon>FaceRecognition.aspx</DependentUpon>
</Compile>
<Compile Include="WeldMat\UsingSentMat\LC700.aspx.cs">
<DependentUpon>LC700.aspx</DependentUpon>
<SubType>ASPXCodeBehind</SubType>
@ -7447,6 +7455,10 @@
<Project>{FD1E1931-1688-4B4A-BCD6-335A81465343}</Project>
<Name>Model</Name>
</ProjectReference>
<ProjectReference Include="..\SgManager.AI\SgManager.AI.csproj">
<Project>{55f4e1e2-5fb3-4ab4-b692-432ce41b3e61}</Project>
<Name>SgManager.AI</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="aspnet_client\FreeTextBox\images\misc\buttonbackgrounds.psd" />

View File

@ -23,6 +23,22 @@
<!--系统:焊接管理为HJGL,焊材管理HJCLGL-->
<add key="SystemCode" value="HJCLGL"/>
<add key="http" value="http://localhost/test/"/>
<!--BAIDU AI配置-->
<add key="APP_ID" value="119624563"/>
<add key="API_KEY" value="qm0iFO9OTHqx5dt5dNIKuvIE"/>
<add key="SECRET_KEY" value="NwA68AnLM9SwEcbB2ONCu6cagy2czzVc"/>
<!--人脸检测参数-->
<!--人脸活体检测参数1最好0最差 建议0.995 -->
<add key="BD_face_liveness" value="0.3"/>
<!--人脸高宽建议100-200-->
<!--<add key="BD_width" value="200" />-->
<!--<add key="BD_height" value="200" />-->
<!--人脸角度-->
<add key="BD_roll" value="40"/>
<!--人脸遮档度0最好1最不好-->
<add key="BD_occlusion" value="1"/>
<!--人脸模糊度0最好1最不好-->
<add key="BD_blur" value="0.1"/>
</appSettings>
<!--
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。

View File

@ -0,0 +1,132 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FaceRecognition.aspx.cs" Inherits="FineUIPro.Web.WeldMat.UsingSentMat.FaceRecognition" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>人脸识别</title>
<style id="Style1" runat="server" type="text/css">
.title
{
font-size:14pt;
font-weight:bold;
text-align:center;
}
video, canvas { border: 1px solid #ccc; margin: 10px; }
button { padding: 8px 16px; margin: 5px; }
</style>
</head>
<body>
<form id="form1" runat="server">
<f:PageManager ID="PageManager1" AutoSizePanelID="Panel1" runat="server" />
<f:Panel ID="Panel1" runat="server" ShowBorder="false" ShowHeader="false" Layout="Region">
<Items>
<f:Panel runat="server" ID="panelCenterRegion" RegionPosition="Center" ShowBorder="true"
Layout="VBox" ShowHeader="true" BodyPadding="5px" IconFont="PlusCircle" Title="人脸识别"
TitleToolTip="人脸识别" AutoScroll="true">
<Items>
<f:ContentPanel ShowBorder="false" ShowHeader="false" ID="ContentPanel1" runat ="server" BodyStyle="text-align:center">
<video id="video" width="480" height="640" autoplay></video>
<canvas id="canvas" width="480" height="640" style="display:none" ></canvas>
<div>
<button id="captureBtn" type="button">识别</button>
</div>
</f:ContentPanel>
</Items>
</f:Panel>
</Items>
</f:Panel>
</form>
<script type="text/javascript">
// 返回false来阻止浏览器右键菜单
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const captureBtn = document.getElementById('captureBtn');
const ctx = canvas.getContext('2d');
let stream = null;
setTimeout(async () => {
try {
stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal:480 },
height: { ideal:640 },
facingMode: "environment" // 后置摄像头
},
audio: false
});
video.srcObject = stream;
} catch (err) {
console.error("摄像头访问错误:", err);
alert(`无法访问摄像头: ${err.message}`);
}
}, 1000)
// 截图功能
document.getElementById('captureBtn').addEventListener('click', () => {
if (!stream) return alert('请先开启摄像头');
if (captureBtn.innerHTML == '识别') {
captureBtn.innerHTML = '重新识别'
canvas.style = "";
video.style = "display:none";
// 适配高DPI屏幕
const scale = window.devicePixelRatio || 1;
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
ctx.scale(scale, scale);
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
// 生成图片下载链接
const imgUrl = canvas.toDataURL('image/jpeg');
upLoadFile(imgUrl)
//const link = document.createElement('a');
//link.download = 'capture-' + new Date().getTime() + '.jpg';
//link.href = imgUrl;
//link.click();
} else {
captureBtn.innerHTML = '识别'
video.style = "";
canvas.style = "display:none";
}
});
function upLoadFile(data) {
$.ajax({
url: "FaceRecognition.aspx/UploadData",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
data: data,
projectId:'<%=CurrUser.LoginProjectId%>'
}),
success: function (data) {
/*window.parent.backData(data.d)*/
alert(data.d)
if (data.d.indexOf('识别失败') !== -1) {
alert('识别失败请重新识别')
}
else {
// window.location.href = 'UsingMat.aspx?welderQRCode=' + data.d ;
window.open('UsingMat.aspx?welderQRCode=' + data.d , '_blank');
//var activeWindow = F.getActiveWindow();
//activeWindow.window.backData(data.d);
//activeWindow.hide();
}
}
})
}
</script>
</body>
</html>

View File

@ -0,0 +1,87 @@
using BLL;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web.Services;
namespace FineUIPro.Web.WeldMat.UsingSentMat
{
public partial class FaceRecognition : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string UploadData(string data,string projectId)
{
byte[] imageBytes = Convert.FromBase64String(data.Substring("data:image/jpeg;base64,".Length));
string filePath = "/FileUpLoad/FaceRecognition/" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpeg";
if (!Directory.Exists(BLL.Funs.RootPath + "/FileUpLoad/FaceRecognition/"))
{
Directory.CreateDirectory(BLL.Funs.RootPath + "/FileUpLoad/FaceRecognition/");
}
// 使用MemoryStream将字节数组转换为图片
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
System.Drawing.Image mImage = System.Drawing.Image.FromStream(ms);
// 使用Bitmap类从MemoryStream创建图片
using (Bitmap image = new Bitmap(mImage))
{
// 保存图片到文件
image.Save(BLL.Funs.RootPath + filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
try
{
var kqFace = (List<SgManager.AI.faceResult>)SgManager.AI.FaceClass.SearchFileFace(BLL.Funs.RootPath + filePath);
if (kqFace == null || kqFace.Count == 0)
{
return "识别失败";
}
else if (kqFace[0].errMess != "SUCCESS")
{
return "识别失败;" + kqFace[0].errMess;
}
else
{
try
{
string idCard = kqFace[0].user_id;
var welder = Funs.DB.HJGL_BS_Welder.FirstOrDefault(x => x.ProjectId == projectId && x.IdentityCard == idCard);
if (welder != null)
{
return welder.WED_Code;
}
else
{
return "识别失败;身份证号"+ idCard+"未找到焊工";
}
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
return "识别失败";
}
}
}

View File

@ -0,0 +1,80 @@
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace FineUIPro.Web.WeldMat.UsingSentMat
{
public partial class FaceRecognition
{
/// <summary>
/// Head1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// Style1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl Style1;
/// <summary>
/// form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// PageManager1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.PageManager PageManager1;
/// <summary>
/// Panel1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Panel Panel1;
/// <summary>
/// panelCenterRegion 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Panel panelCenterRegion;
/// <summary>
/// ContentPanel1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.ContentPanel ContentPanel1;
}
}

View File

@ -85,6 +85,16 @@
</f:Image>
</Items>
</f:FormRow>
<f:FormRow>
<Items>
<f:FileUpload ID="filePhoto1" runat="server" ButtonText="上传头像到百度" ButtonOnly="true"
AutoPostBack="true" OnFileSelected="filePhoto1_FileSelected">
</f:FileUpload>
<f:Image ID="imgPhoto1" CssClass="userphoto" runat="server" BoxFlex="1" MarginLeft="10px">
</f:Image>
</Items>
</f:FormRow>
</Rows>
<Toolbars>
<f:Toolbar ID="Toolbar1" Position="Top" runat="server" ToolbarAlign="Right">

View File

@ -1,13 +1,18 @@
namespace FineUIPro.Web.common.WelderManage
{
using System;
using System.Drawing;
using BLL;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SgManager.AI;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using System.Text;
using System.IO;
public partial class WelderSave : PageBase
{
@ -225,6 +230,8 @@
welder.ProjectId = this.CurrUser.LoginProjectId;
welder.AttachUrl = this.AttachUrl;
welder.SignatureUrl = imgPhoto.ImageUrl;
welder.PhotoUrl = imgPhoto1.ImageUrl;
welder.IsOAM = true;
if (string.IsNullOrEmpty(this.WED_ID))
{
@ -237,9 +244,125 @@
BLL.HJGL_PersonManageService.UpdateBSWelder(welder);
BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, "修改人员信息!");
}
if (!string.IsNullOrEmpty(welder.PhotoUrl) )
{
Alert.ShowInParent(PersonFace(welder), MessageBoxIcon.Warning);
}
}
#endregion
public string PersonFace(Model.HJGL_BS_Welder person)
{
string message = string.Empty;
string filePath = Server.MapPath("~/") + person.PhotoUrl;
List<SgManager.AI.faceResult> kqFace = null;
try
{
kqFace = (List<SgManager.AI.faceResult>)SgManager.AI.FaceClass.SearchFileFace(filePath);
if (kqFace != null || kqFace.Count > 0 || kqFace[0].errMess == "SUCCESS")
{
string result = FaceClass.FaceVerify(filePath);
JObject jresult = JObject.Parse(result);
JObject lvresult = jresult.Value<JObject>("result");
bool isOK = false;
if (jresult.Value<int>("error_code") == 0)
{
if (lvresult.Value<double>("face_liveness") >= ConfigAppSetting.getConfigAppSetting("BD_face_liveness") ? true : false)//99.5%//活体度
{
if (Convert.ToDouble(lvresult["face_list"][0]["location"]["width"]) > ConfigAppSetting.getConfigAppSetting("BD_width") ? true : false)
{
if (Convert.ToDouble(lvresult["face_list"][0]["location"]["height"]) > ConfigAppSetting.getConfigAppSetting("BD_height") ? true : false)
{
if (System.Math.Abs(Convert.ToDouble(lvresult["face_list"][0]["angle"]["roll"])) <= ConfigAppSetting.getConfigAppSetting("BD_roll") ? true : false)//角度正负度数
{
if (System.Math.Abs(Convert.ToDouble(lvresult["face_list"][0]["angle"]["yaw"])) <= ConfigAppSetting.getConfigAppSetting("BD_roll") + 1 ? true : false)//角度正负度数
{
if (System.Math.Abs(Convert.ToDouble(lvresult["face_list"][0]["angle"]["pitch"])) <= ConfigAppSetting.getConfigAppSetting("BD_roll") + 1 ? true : false)//角度正负度数
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["left_eye"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["right_eye"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["nose"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["mouth"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["left_cheek"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["right_cheek"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["occlusion"]["chin_contour"]) <= ConfigAppSetting.getConfigAppSetting("BD_occlusion") ? true : false)// 0为无遮挡1是完全遮挡
{
if (Convert.ToDouble(lvresult["face_list"][0]["quality"]["blur"]) <= ConfigAppSetting.getConfigAppSetting("BD_blur") ? true : false)//模糊度0---1小于0.7
{ isOK = true; }
else message = "清晰度检测失败"; ;
}
else message = "遮挡检测失败";
}
else message = "遮挡检测失败";
}
else message = "遮挡检测失败";
}
else message = "遮挡检测失败";
}
else message = "遮挡检测失败";
}
else message = "遮挡检测失败";
}
else message = "遮挡检测失败";
}
else message = "角度检测失败";
}
else message = "角度检测失败";
}
else message = "角度检测失败";
}
else message = "宽高检测失败";
}
else message = "宽高检测失败";
}
else message = "人脸动态检测失败";
}
else message = "识别不到人脸";
if (isOK)
{
var faceResult = FaceClass.add(person.WED_ID, person.IdentityCard, System.Configuration.ConfigurationManager.AppSettings["HJGLUrl"].ToString() + person.PhotoUrl, AccessToken.getAccessToken());
var face = JsonConvert.DeserializeObject<dynamic>(faceResult);
// JsonConvert.DeserializeObject<dynamic>(myPunishItem);
if (face.error_code == 0 || face.error_code == 223105)
{
message = "人脸库注册成功!";
// face_token = face.result.face_token;
//APIPersonService.SaveSitePerson(person);
}
else
{
message = "注册人脸库失败" + face.error_code + face.error_msg;
}
}
else
{
message += "注册人脸库失败";
}
}
}
catch (Exception ex)
{
message = "注册人脸库失败";
ErrLogInfo.WriteLog(ex, "PC-人员信息保存", "SitePerson.PersonListEdit");
}
return message;
}
#region
/// <summary>
/// 上传照片
@ -264,6 +387,27 @@
filePhoto.Reset();
}
}
protected void filePhoto1_FileSelected(object sender, EventArgs e)
{
if (filePhoto1.HasFile)
{
string fileName = filePhoto1.ShortFileName;
if (!ValidateFileType(fileName))
{
ShowNotify("无效的文件类型!");
return;
}
fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;
filePhoto1.SaveAs(Server.MapPath("~/upload/" + fileName));
imgPhoto1.ImageUrl = "~/upload/" + fileName;
// 清空文件上传组件
filePhoto1.Reset();
}
}
#endregion
//protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
//{

View File

@ -7,11 +7,13 @@
// </自动生成>
//------------------------------------------------------------------------------
namespace FineUIPro.Web.common.WelderManage {
public partial class WelderSave {
namespace FineUIPro.Web.common.WelderManage
{
public partial class WelderSave
{
/// <summary>
/// form1 控件。
/// </summary>
@ -20,7 +22,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// PageManager1 控件。
/// </summary>
@ -29,7 +31,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.PageManager PageManager1;
/// <summary>
/// SimpleForm1 控件。
/// </summary>
@ -38,7 +40,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Form SimpleForm1;
/// <summary>
/// drpUnit 控件。
/// </summary>
@ -47,7 +49,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.DropDownList drpUnit;
/// <summary>
/// txtRecordDate 控件。
/// </summary>
@ -56,7 +58,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.DatePicker txtRecordDate;
/// <summary>
/// txtName 控件。
/// </summary>
@ -65,7 +67,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.TextBox txtName;
/// <summary>
/// txtCode 控件。
/// </summary>
@ -74,7 +76,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.TextBox txtCode;
/// <summary>
/// txtBirthday 控件。
/// </summary>
@ -83,7 +85,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.DatePicker txtBirthday;
/// <summary>
/// drpSex 控件。
/// </summary>
@ -92,7 +94,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.RadioButtonList drpSex;
/// <summary>
/// txtWorkCode 控件。
/// </summary>
@ -101,7 +103,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.TextBox txtWorkCode;
/// <summary>
/// txtLimitDate 控件。
/// </summary>
@ -110,7 +112,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.DatePicker txtLimitDate;
/// <summary>
/// txtClass 控件。
/// </summary>
@ -119,7 +121,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.TextBox txtClass;
/// <summary>
/// drpIfOnGuard 控件。
/// </summary>
@ -128,7 +130,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.CheckBox drpIfOnGuard;
/// <summary>
/// txtIdentityCard 控件。
/// </summary>
@ -137,7 +139,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.TextBox txtIdentityCard;
/// <summary>
/// btnQR 控件。
/// </summary>
@ -146,7 +148,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Button btnQR;
/// <summary>
/// btnSee 控件。
/// </summary>
@ -155,7 +157,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Button btnSee;
/// <summary>
/// txtRemark 控件。
/// </summary>
@ -164,7 +166,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.TextArea txtRemark;
/// <summary>
/// filePhoto 控件。
/// </summary>
@ -173,7 +175,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.FileUpload filePhoto;
/// <summary>
/// imgPhoto 控件。
/// </summary>
@ -182,7 +184,25 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Image imgPhoto;
/// <summary>
/// filePhoto1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.FileUpload filePhoto1;
/// <summary>
/// imgPhoto1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Image imgPhoto1;
/// <summary>
/// Toolbar1 控件。
/// </summary>
@ -191,7 +211,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Toolbar Toolbar1;
/// <summary>
/// lbWelderRead 控件。
/// </summary>
@ -200,7 +220,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Button lbWelderRead;
/// <summary>
/// btnWelderFaceRead 控件。
/// </summary>
@ -209,7 +229,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Button btnWelderFaceRead;
/// <summary>
/// btnSave 控件。
/// </summary>
@ -218,7 +238,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Button btnSave;
/// <summary>
/// Window1 控件。
/// </summary>
@ -227,7 +247,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Window Window1;
/// <summary>
/// Window2 控件。
/// </summary>
@ -236,7 +256,7 @@ namespace FineUIPro.Web.common.WelderManage {
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::FineUIPro.Window Window2;
/// <summary>
/// Window3 控件。
/// </summary>

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\":\"Face\",\"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\":\"Face\",\"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>