Prechádzať zdrojové kódy

Merge branch 'develop' of http://132.232.92.186:3000/XinXiBu/OA2023 into develop

LEIYI 1 rok pred
rodič
commit
89e401a89e

+ 92 - 0
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -8,6 +8,7 @@ using EyeSoft.Runtime.InteropServices;
 using Google.Protobuf.WellKnownTypes;
 using Microsoft.AspNetCore.Mvc.RazorPages;
 using Microsoft.AspNetCore.SignalR;
+using Microsoft.EntityFrameworkCore.Metadata.Internal;
 using Microsoft.IdentityModel.Tokens;
 using Microsoft.VisualBasic;
 using MySqlX.XDevAPI.Relational;
@@ -24,6 +25,7 @@ using OASystem.API.OAMethodLib.File;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.API.OAMethodLib.JuHeAPI;
+using OASystem.API.OAMethodLib.KiMiApi;
 using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
 using OASystem.Domain.AesEncryption;
 using OASystem.Domain.Attributes;
@@ -36,6 +38,7 @@ using OASystem.Domain.Entities.Financial;
 using OASystem.Domain.Entities.Groups;
 using OASystem.Domain.ViewModels.Financial;
 using OASystem.Domain.ViewModels.Groups;
+using OASystem.Domain.ViewModels.OCR;
 using OASystem.Domain.ViewModels.QiYeWeChat;
 using OASystem.Domain.ViewModels.Statistics;
 using OASystem.Infrastructure.Repositories.CRM;
@@ -54,6 +57,7 @@ using System.Drawing.Printing;
 using System.Globalization;
 using System.IO;
 using System.IO.Compression;
+using System.Reflection;
 using System.Text.Json;
 using System.Web;
 using System.Xml.Linq;
@@ -21279,6 +21283,94 @@ ORDER by  gctggrc.id DESC
             public string Job { get; set; }
         }
 
+        [HttpPost]
+        public async Task<IActionResult> FileReadClient(List<IFormFile> files)
+        {
+
+            if (files.Count == 0)
+            {
+                return Ok(JsonView(false, "文件为空"));
+            }
+
+            KiMiApiClient KiMiApi = new KiMiApiClient();
+
+            var seedConter = await KiMiApi.UploadFilesAsync(files);
+
+            if (seedConter.Count == 0)
+            {
+                return Ok(JsonView(false, "上传结果为空!"));
+            }
+
+            var messages = new List<SeedMessages>
+            {
+                new SeedMessages { Role = KimiRole.system, Content = "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。" },
+                new SeedMessages { Role = KimiRole.user, Content = "根据文件内容 ,按照“姓、名、姓名拼音、性别、单位、职务、出生日期”的json格式来排列整理(性别和出生日期通过身份证来识别 , 当识别到性别为男时值给0女给1 未识别到性别的情况下值给-1,出生日期按照yyyy-MM-dd来整理,文件存在拼音的情况读取对应的拼音不存在则设置拼音为中文名字全拼),只输出JSON数组数据 从'['开始 到']'结尾 ,不要除JSON数据外的任何文字以及符号" }
+            };
+
+            messages.InsertRange(1, seedConter);
+
+            var kimiApiResult = await KiMiApi.SeedMessage(messages);
+            var kimiApiResult_JObject = JObject.Parse(kimiApiResult);
+            string clients = kimiApiResult_JObject["content"].ToString();
+
+            string startStr = "```json", endStr = "```";
+
+            // 判断并清除开头部分
+            if (clients.StartsWith(startStr))
+            {
+                clients = clients.Remove(0, startStr.Length);
+            }
+
+            // 判断并清除结尾部分
+            if (clients.EndsWith(endStr))
+            {
+                clients = clients.Remove(clients.Length - endStr.Length);
+            }
+
+            var clients_JObject = JsonConvert.DeserializeObject<List<JObject>>(clients);
+
+            Dictionary<string, string> clientFieldMap = new Dictionary<string, string>()
+            {
+                {"姓", "LastName" },
+                {"名", "FirstName" },
+                {"姓名拼音", "Pinyin" },
+                {"性别", "Sex" },
+                {"单位", "CompanyFullName" },
+                {"职务", "Job" },
+                {"出生日期", "Birthday" },
+            };
+
+            List<BaiduClientOCRView> crmClients = new List<BaiduClientOCRView>();
+
+            foreach (var item in clients_JObject)
+            {
+                BaiduClientOCRView cdc = new BaiduClientOCRView();
+
+                foreach (var field in clientFieldMap.Keys)
+                {
+                    if (item.TryGetValue(field, out JToken value))
+                    {
+                        var getValue = value.ToString();
+                        System.Type type = cdc.GetType();
+                        PropertyInfo propertyInfo = type.GetProperty(clientFieldMap[field]);
+                        var propertyValue = Convert.ChangeType(getValue, propertyInfo.PropertyType);
+                        propertyInfo.SetValue(cdc, propertyValue);
+                    }
+                }
+
+                crmClients.Add(cdc);
+            }
+
+
+            return Ok(JsonView(new
+            {
+                fileCount = files.Count,
+                UploadCount = seedConter.Count,
+                ApiResult = clients,
+                CrmClients = crmClients
+            }));
+        }
+
         #endregion
 
         #region 团组倒推表

+ 142 - 0
OASystem/OASystem.Api/OAMethodLib/KiMiApi/KiMiApi.cs

@@ -0,0 +1,142 @@
+
+using System.Net.Http.Headers;
+
+namespace OASystem.API.OAMethodLib.KiMiApi
+{
+    public class KiMiApiClient
+    {
+        private readonly HttpClient _httpClient;
+
+        public KiMiApiClient()
+        {
+            _httpClient = new HttpClient();
+
+            // 设置公共请求头
+            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
+        }
+
+        private  string apiKey = "sk-AY1Sv4rLnSUgGGHcC8SGSWYYKzGID7leZJcFfxAYozLC8dIc";
+        private  string baseUrl = "https://api.moonshot.cn/v1";
+
+        public async Task<string> UploadFileAsync(IFormFile file)
+        {
+            string message = string.Empty;
+
+            byte[] fileBytes = null;
+
+            using (var memoryStream = new MemoryStream())
+            {
+                await file.CopyToAsync(memoryStream);
+                fileBytes = memoryStream.ToArray();
+            }
+
+            // 上传文件
+            var fileContent = new ByteArrayContent(fileBytes);
+
+            var fileFormData = new MultipartFormDataContent
+            {
+                { fileContent, "file", file.FileName },
+                { new StringContent("file-extract"), "purpose" }
+            };
+
+            HttpResponseMessage fileResponse = await _httpClient.PostAsync($"{baseUrl}/files", fileFormData);
+            string fileResponseContent = await fileResponse.Content.ReadAsStringAsync();
+
+            if (!fileResponse.IsSuccessStatusCode)
+            {
+                throw new Exception($"Failed to upload file: {fileResponseContent}");
+            }
+
+            dynamic fileObject = JsonConvert.DeserializeObject(fileResponseContent);
+            string fileId = fileObject.id;
+
+            HttpResponseMessage contentResponse = await _httpClient.GetAsync($"{baseUrl}/files/{fileId}/content");
+            string fileContentText = await contentResponse.Content.ReadAsStringAsync();
+
+            if (!contentResponse.IsSuccessStatusCode)
+            {
+                throw new Exception($"Failed to get file content: {fileContentText}");
+            }
+
+            message = fileContentText;
+
+
+            return message;
+        }
+
+        public async Task<List<SeedMessages>> UploadFilesAsync(List<IFormFile> files)
+        {
+            List<SeedMessages> result = new List<SeedMessages>();
+
+            foreach (IFormFile file in files)
+            {
+                var fileConter = await this.UploadFileAsync(file);
+                result.Add(new SeedMessages() { Role = KimiRole.system , Content = fileConter });
+            }
+
+
+            return result;
+        }
+
+        public async Task<string> SeedMessage(List<SeedMessages> messages)
+        {
+
+            //读取配置文件
+            var kimiModel = AppSettingsHelper.Get("KiMiModel");
+
+            var completionRequest = new
+            {
+                model = kimiModel,
+                messages = messages.Select(x=> new
+                {
+                    Role = StringEnumHelper.ToStringValue(x.Role),
+                    x.Content
+                }),
+                temperature = 1
+            };
+
+            var completionJson = JsonConvert.SerializeObject(completionRequest);
+            var completionContent = new StringContent(completionJson, Encoding.UTF8, "application/json");
+
+            HttpResponseMessage completionResponse = await _httpClient.PostAsync($"{baseUrl}/chat/completions", completionContent);
+            string completionResponseContent = await completionResponse.Content.ReadAsStringAsync();
+
+            if (!completionResponse.IsSuccessStatusCode)
+            {
+                throw new Exception($"Failed to seed message: {completionResponseContent}");
+            }
+
+            // 解析返回的完成结果
+            var completion = JObject.Parse(completionResponseContent);
+            string reply = completion["choices"][0]["message"].ToString();
+            return reply;
+        }
+    }
+
+    public class SeedMessages
+    {
+        public KimiRole Role { get; set; }
+
+        public string Content { get; set; }
+    }
+
+    public enum KimiRole
+    {
+        system,
+        user
+    }
+
+    public static class StringEnumHelper
+    {
+        public static string ToStringValue(KimiRole value)
+        {
+            return value switch
+            {
+                KimiRole.system => "system",
+                KimiRole.user => "user",
+                _ => throw new ArgumentOutOfRangeException(nameof(value), value, null)
+            };
+        }
+    }
+
+}

+ 2 - 1
OASystem/OASystem.Api/appsettings.json

@@ -435,5 +435,6 @@
         }
       ]
     }
-  ]
+  ],
+  "KiMiModel": "moonshot-v1-8k"
 }

+ 2 - 1
OASystem/OASystem.Domain/Dtos/Groups/TourClientListDto.cs

@@ -1,4 +1,5 @@
-using Newtonsoft.Json;
+using Microsoft.AspNetCore.Http;
+using Newtonsoft.Json;
 using OASystem.Domain.Attributes;
 using System;
 using System.Collections.Generic;