Signed-off-by: 高源 <3056440880@qq.com>
Dev
高源 1 year ago
parent 37c0b62200
commit f0dc16fc75

@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}

Binary file not shown.

Binary file not shown.

@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfApp1.WinOcr;
using WpfApp1.ScnToJson;
using WpfApp1.translationKey;
using WpfApp1.transToNet;
namespace testRjgc
{
internal class AllClassAndInterfaceWellBeManipulatedInThisFileAndCallThroughFunction
{
public AllClassAndInterfaceWellBeManipulatedInThisFileAndCallThroughFunction() { }
TranslationPrivateIn trin = new TranslationPrivateIn();
TranslationApiStr trstr = new translationPrivateOut();
TranslationApiInt trint = new translationPublic();
TranslationScnToJson scnjson = new TranslationScnToJson();
Sofia sof = new OcrSofia();
Messiah jsonnet = new jsonNet();
public void InputPrivateBaidu(string name, string id, string key)
{
trin.InputBaiduPrivate(name, id, key);
}
public void InPutPrivateA(string name, List<string> list)
{
trin.InPutPrivate(name, list);
}
public List<string> OutputNameList()
{
List<string> list = trstr.OutputTranslationNameList();
return list;
}
public List<string> OutputStr(string id)
{
List<string> li = trstr.OutputTranslationS(id);
return li;
}
public List<string> OutputChoicPublic(int id)
{
List<string> li = trint.OutputTranslationI(id);
return li;
}
public void StartSCNTransJSON()
{
scnjson.StartTrans();
}
public void StartTransOneself(string spa, string dps)
{
scnjson.StopTrans(spa, dps);
}
public string WindowsOcrToGetString(string name)
{
return sof.WindowsOcrToGetStringAndTranslate(name);
}
public string NetBaiDu(string input)
{
return jsonnet.RequestJsonBaiDu(input);
}
public string NetAllBaiDu(string input, string srcl, string dstl, string aid, string kkey)
{
return jsonnet.RequestJsonPrivateBaiDu(input, srcl, dstl, aid, kkey);
}
public string NetLanBaiDu(string input, string srcl, string dstl)
{
return jsonnet.RequestJsonLanguageChangeBaiDu(input, srcl, dstl);
}
public string NetXunFei(string input)
{
return jsonnet.RequestJsonXunFei(input);
}
public string NetLanXunFei(string input, string srcl, string dstl)
{
return jsonnet.RequestJsonLanguageChangeXunFei(input, srcl, dstl);
}
public string NetAllXunFei(string input, string srcl, string dstl, string xid, string xsecret, string xkey)
{
return jsonnet.RequestJsonPrivateXunFei(input, srcl, dstl, xid, xsecret, xkey);
}
}
}
/*
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace OCRConsoleApp
{
class Program
{
static void Main(string[] args)
{
using IHost host = CreateHostBuilder(args).Build();
var ocrService = host.Services.GetRequiredService<IOcrService>();
// 截图并保存到本地文件
var bitmap = ocrService.CaptureScreen();
bitmap.Save("screenshot.png", ImageFormat.Png);
// 识别图片中的文字
var text = ocrService.RecognizeText(bitmap);
Console.WriteLine(text);
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddSingleton<IOcrService>(new OcrService());
});
}
public interface IOcrService
{
Bitmap CaptureScreen();
string RecognizeText(Bitmap bitmap);
}
public class OcrService : IOcrService
{
public Bitmap CaptureScreen()
{
var screenBounds = ScreenHelper.GetScreenBounds();
var bitmap = new Bitmap(screenBounds.Width, screenBounds.Height);
using (var graphics = Graphics.FromImage(bitmap))
graphics.CopyFromScreen(screenBounds.X, screenBounds.Y, 0, 0, screenBounds.Size);
return bitmap;
}
public string RecognizeText(Bitmap bitmap)
{
var ocrEngine = new IronOcr.AutoOcr();
var result = ocrEngine.Read(bitmap);
return result.Text;
}
}
public static class ScreenHelper
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool GetCursorPos(out Point lpPoint);
public static Rectangle GetScreenBounds()
{
GetCursorPos(out Point point);
var screenBounds = Screen.FromPoint(point).Bounds;
return screenBounds;
}
}
}
*/

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.transToNet
{
/*
internal class GrapeToJsonTrans : GrapeToJson
{
public List<string> GrapeRequestJson()
{
List<string> re = new List<string>();
return re;
}
public List<string> GrapeRequestJsonBaiDu()
{
List<string> re = new List<string>();
return re;
}
public List<string> GrapeRequestJsonLanguageChange()
{
List<string> re = new List<string>();
return re;
}
}
*/
}

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.transToNet
{
interface Messiah
{
public abstract string RequestJsonPrivateBaiDu(string input, string srcl, string dstl, string aid, string kkey);
public abstract string RequestJsonLanguageChangeBaiDu(string input, string srcl, string dstl);
public abstract string RequestJsonBaiDu(string input);
//以下接口暂时废弃
public abstract string RequestJsonXunFei(string input);
public abstract string RequestJsonPrivateXunFei(string input, string srcl, string dstl, string xid, string xsecret, string xkey);
public abstract string RequestJsonLanguageChangeXunFei(string input, string srcl, string dstl);
}
/*
interface GrapeToJson
{
public abstract List<string> GrapeRequestJson();
public abstract List<string> GrapeRequestJsonLanguageChange();
public abstract List<string> GrapeRequestJsonBaiDu();
}
*/
}

@ -0,0 +1,642 @@
using Newtonsoft.Json;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
namespace WpfApp1.transToNet
{
internal class jsonNet : Messiah
{
static string https = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
static string appid = "20230925001829663";//20230925001829663,20230923001827495
static Random rd = new Random();
static string salt = rd.Next(100000).ToString();
static string key = "f7ZHpw28izQ1VU_ixoY5";//f7ZHpw28izQ1VU_ixoY5,yjvMNY33Qc1TYSBjTQYQ
//baidu
static string xunweb = "https://itrans.xf-yun.com/v1/its";
static string xunid = "1299c840";
static string xunsec = "M2Q4YzkzZTIwZjNkMGE2ZjkwZWMxNzZk";
static string xunkey = "828cb2dc915d28464a904bda5d7b01b3";
static string xunfl = "en";//ja
static string xundl = "cn";
static string xuntxt = "Sakura miko";
//static HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=20230925001829663&salt=1435660288&sign=c963bc2275c0fd1ed30da014c1ef1933");
/*
private static HttpClient HttpRe = new HttpClient()
{
BaseAddress = new Uri("http://api.fanyi.baidu.com/api/trans/vip/translate?"),
};
static async Task GetAsync(HttpClient httpc)
{
using HttpResponseMessage response = await httpc.GetAsync(temp);
//var value = response.EnsureSuccessStatusCode().WriteRequestToConsole();
var jsonResponse = await response.Content.ReadAsStringAsync();//收到json
Console.WriteLine($"{jsonResponse}\n");
}
*/
private HttpClient HttpRequestC(string url)//创建HTTP
{
HttpClient httpClient = new HttpClient()
{
BaseAddress = new Uri(url)
};
return httpClient;
}
private static string EncryptString(string str)//百度MD5加密计算方式
{
MD5 md5 = MD5.Create();
// 将字符串转换成字节数组
byte[] byteOld = Encoding.UTF8.GetBytes(str);
// 调用加密方法
byte[] byteNew = md5.ComputeHash(byteOld);
// 将加密结果转换为字符串
StringBuilder sb = new StringBuilder();
foreach (byte b in byteNew)
{
// 将字节转换成16进制表示的字符串
sb.Append(b.ToString("x2"));
}
// 返回加密的字符串
return sb.ToString();
}
private static string HmacSha256(string message, string secret)//hmachas256加密
{
byte[] keyBytes = Encoding.UTF8.GetBytes(secret);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
{
byte[] signatureBytes = hmac.ComputeHash(messageBytes);
return Convert.ToBase64String(signatureBytes);
}
}
private static string Sha256(string message)//SHA-256加密
{
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
using (SHA256 sha256 = SHA256.Create())
{
byte[] signatureBytes = sha256.ComputeHash(messageBytes);
return Convert.ToBase64String(signatureBytes);
}
}
private static string signBody(string body)
{
byte[] messageBytes = Encoding.UTF8.GetBytes(body);
using (SHA256 sha256 = SHA256.Create())
{
byte[] signatureBytes = sha256.ComputeHash(messageBytes);
string signature = Convert.ToBase64String(signatureBytes);
return hmacsign(signature, xunsec);
}
}
private static string hmacsign(string signature, string apiSecret)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(apiSecret);
byte[] messageBytes = Encoding.UTF8.GetBytes(signature);
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
{
byte[] signatureBytes = hmac.ComputeHash(messageBytes);
return Convert.ToBase64String(signatureBytes);
}
}
private static string ComputeSha256(string message)
{
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
using (SHA256 sha256 = SHA256.Create())
{
byte[] signatureBytes = sha256.ComputeHash(messageBytes);
return Convert.ToBase64String(signatureBytes);
}
}
private static string BuildHttpBody()
{
Dictionary<string, object> paramMap = new()
{
{ "from", "cn" },
{ "to", "en" },
{ "appid", xunid },
{ "salt", DateTime.Now.Millisecond.ToString() },
{ "signType", "v3" },
{ "signature", "" },
{ "voice", "0" },
{ "text", "你好,世界!" }
};
string body = JsonConvert.SerializeObject(paramMap);
string signature = signBody(body);
paramMap["signature"] = signature;
return JsonConvert.SerializeObject(paramMap);
}
private static Dictionary<string, string> BuildHttpHeader(string body)
{
string curTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string param = xunkey + curTime + body;
string checkSum = ComputeSha256(param);
Dictionary<string, string> header = new()
{
{ "Content-Type", "application/json" },
{ "X-Appid", xunid },
{ "X-CurTime", curTime },
{ "X-Param", body },
{ "X-CheckSum", checkSum }
};
return header;
}
public string RequestJsonPrivateBaiDu(string input, string srcl, string dstl, string aid, string kkey)//自定义idkey以及源语言和目标语言
{
string sign = EncryptString(aid + input + salt + kkey);
string temp = "q=" + HttpUtility.UrlEncode(input) + "&from=" + srcl + "&to=" + dstl + "&appid=" + aid + "&salt=" + salt + "&sign=" + sign;
Console.WriteLine(https + temp);
//Task t = GetAsync(HttpRe); t.Wait();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(https + temp);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.UserAgent = null;
request.Timeout = 6000;
var response = request.GetResponse();
var myResponseStream = response.GetResponseStream();
var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
tempC2 temp1 = JsonConvert.DeserializeObject<tempC2>(retString);
Trans_result result = temp1.trans_result[0];
string s = result.dst;
return s;
}
public string RequestJsonLanguageChangeBaiDu(string input, string srcl, string dstl)//可以自定义源语言与目标语言
{
string sign = EncryptString(appid + input + salt + key);
string temp = "q=" + HttpUtility.UrlEncode(input) + "&from=" + srcl + "&to=" + dstl + "&appid=" + appid + "&salt=" + salt + "&sign=" + sign;
Console.WriteLine(https + temp);
//Task t = GetAsync(HttpRe); t.Wait();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(https + temp);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.UserAgent = null;
request.Timeout = 6000;
var response = request.GetResponse();
var myResponseStream = response.GetResponseStream();
var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
tempC2 temp1 = JsonConvert.DeserializeObject<tempC2>(retString);
Trans_result result = temp1.trans_result[0];
string s = result.dst;
return s;
}
public string RequestJsonBaiDu(string input)//默认
{
string sign = EncryptString(appid + input + salt + key);
string temp = "q=" + HttpUtility.UrlEncode(input) + "&from=jp&to=zh&appid=" + appid + "&salt=" + salt + "&sign=" + sign;
Console.WriteLine(https + temp);
//Task t = GetAsync(HttpRe); t.Wait();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(https + temp);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.UserAgent = null;
request.Timeout = 6000;
var response = request.GetResponse();
var myResponseStream = response.GetResponseStream();
var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
tempC2 temp1 = JsonConvert.DeserializeObject<tempC2>(retString);
Trans_result result = temp1.trans_result[0];
string s = result.dst;
return s;
}
public string RequestJsonXunFei(string input)
{
// 接口地址
string host = "itrans.xfyun.cn";
string url = string.Format("https://{0}/v2/its", host);
// 原文
string q = "amyotrophic lateral sclerosis";
q = input;
// 源语言
string from = "ja";
// 目标语言
string to = "cn";
string apikey = "a31395d71149fc5f1e73353f56d3d726";
string apisecret = "YWVhYWUyM2YyMTAyMDdhYTk3YTRhMjli";
string appid = "56e76335";
string requestJson = HttpUtil.BuildXunFeiRequestJson(appid, from, to, q);
string Digest = "SHA-256=" + HttpUtil.ComputeHash256_base64(requestJson, new SHA256CryptoServiceProvider());
DateTime dateTime = DateTime.UtcNow;
string dateStr = dateTime.ToString("r");
string signature = string.Format("host: {0}\ndate: {1}\nPOST /v2/its HTTP/1.1\ndigest: {2}", host, dateStr, Digest);
string signature_sha = HttpUtil.hmacsha256(signature, apisecret);
string Authorization = string.Format("api_key=\"{0}\", algorithm=\"hmac-sha256\", headers=\"host date request-line digest\", signature=\"{1}\"", apikey, signature_sha);
//post
byte[] byteArray = Encoding.UTF8.GetBytes(requestJson);
HttpWebRequest httpWebRequest;
//HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpUtil.CheckValidationResult);
httpWebRequest.ProtocolVersion = HttpVersion.Version11;
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2;
httpWebRequest.KeepAlive = false;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
}
else
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = byteArray.Length;
httpWebRequest.Accept = "application/json";
httpWebRequest.Date = dateTime;
httpWebRequest.Host = host;
httpWebRequest.Headers.Add("Digest", Digest);
httpWebRequest.Headers.Add("Authorization", Authorization);
httpWebRequest.KeepAlive = false;
int respondCode = 0;
string translation = string.Empty;
string respondStr = string.Empty;
try
{
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
respondCode = (int)webResponse.StatusCode;
if (respondCode == 200)
{
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
respondStr = sr.ReadToEnd();
}
dynamic TempResult = JsonConvert.DeserializeObject(respondStr);
respondStr = Convert.ToString(TempResult["data"]["result"]["trans_result"]["dst"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return respondStr;
}
public string RequestJsonPrivateXunFei(string input, string srcl, string dstl, string xid, string xse , string xkey)
{
// 接口地址
string host = "itrans.xfyun.cn";
string url = string.Format("https://{0}/v2/its", host);
// 原文
string q = "";
q = input;
// 源语言
string from = srcl;
// 目标语言
string to = dstl; //"cn";
string apikey = xkey;
string apisecret = xse;
string appid = xid;
string requestJson = HttpUtil.BuildXunFeiRequestJson(appid, from, to, q);
string Digest = "SHA-256=" + HttpUtil.ComputeHash256_base64(requestJson, new SHA256CryptoServiceProvider());
DateTime dateTime = DateTime.UtcNow;
string dateStr = dateTime.ToString("r");
string signature = string.Format("host: {0}\ndate: {1}\nPOST /v2/its HTTP/1.1\ndigest: {2}", host, dateStr, Digest);
string signature_sha = HttpUtil.hmacsha256(signature, apisecret);
string Authorization = string.Format("api_key=\"{0}\", algorithm=\"hmac-sha256\", headers=\"host date request-line digest\", signature=\"{1}\"", apikey, signature_sha);
//post
byte[] byteArray = Encoding.UTF8.GetBytes(requestJson);
HttpWebRequest httpWebRequest;
//HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpUtil.CheckValidationResult);
httpWebRequest.ProtocolVersion = HttpVersion.Version11;
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2;
httpWebRequest.KeepAlive = false;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
}
else
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = byteArray.Length;
httpWebRequest.Accept = "application/json";
httpWebRequest.Date = dateTime;
httpWebRequest.Host = host;
httpWebRequest.Headers.Add("Digest", Digest);
httpWebRequest.Headers.Add("Authorization", Authorization);
httpWebRequest.KeepAlive = false;
int respondCode = 0;
string translation = string.Empty;
string respondStr = string.Empty;
try
{
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
respondCode = (int)webResponse.StatusCode;
if (respondCode == 200)
{
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
respondStr = sr.ReadToEnd();
}
dynamic TempResult = JsonConvert.DeserializeObject(respondStr);
// 这是返回的 译文
respondStr = Convert.ToString(TempResult["data"]["result"]["trans_result"]["dst"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return respondStr;
}
public string RequestJsonLanguageChangeXunFei(string input, string srcl, string dstl)
{
// 接口地址
string host = "itrans.xfyun.cn";
string url = string.Format("https://{0}/v2/its", host);
// 原文
string q = "";
q = input;
// 源语言
string from = srcl;
// 目标语言
string to = dstl;
string apikey = "a31395d71149fc5f1e73353f56d3d726";
string apisecret = "YWVhYWUyM2YyMTAyMDdhYTk3YTRhMjli";
string appid = "56e76335";
string requestJson = HttpUtil.BuildXunFeiRequestJson(appid, from, to, q);
string Digest = "SHA-256=" + HttpUtil.ComputeHash256_base64(requestJson, new SHA256CryptoServiceProvider());
DateTime dateTime = DateTime.UtcNow;
string dateStr = dateTime.ToString("r");
string signature = string.Format("host: {0}\ndate: {1}\nPOST /v2/its HTTP/1.1\ndigest: {2}", host, dateStr, Digest);
string signature_sha = HttpUtil.hmacsha256(signature, apisecret);
string Authorization = string.Format("api_key=\"{0}\", algorithm=\"hmac-sha256\", headers=\"host date request-line digest\", signature=\"{1}\"", apikey, signature_sha);
//post
byte[] byteArray = Encoding.UTF8.GetBytes(requestJson);
HttpWebRequest httpWebRequest;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpUtil.CheckValidationResult);
httpWebRequest.ProtocolVersion = HttpVersion.Version11;
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2;
httpWebRequest.KeepAlive = false;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
}
else
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = byteArray.Length;
httpWebRequest.Accept = "application/json";
httpWebRequest.Date = dateTime;
httpWebRequest.Host = host;
httpWebRequest.Headers.Add("Digest", Digest);
httpWebRequest.Headers.Add("Authorization", Authorization);
httpWebRequest.KeepAlive = false;
int respondCode = 0;
string translation = string.Empty;
string respondStr = string.Empty;
try
{
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
respondCode = (int)webResponse.StatusCode;
if (respondCode == 200)
{
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
respondStr = sr.ReadToEnd();
}
dynamic TempResult = JsonConvert.DeserializeObject(respondStr);
// 接收到的 译文
respondStr = Convert.ToString(TempResult["data"]["result"]["trans_result"]["dst"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return respondStr;
}
}
class Trans_result
{
public string src { get; set; }
public string dst { get; set; }
}
class tempC2
{
public List<Trans_result> trans_result { get; set; }
}
class ResponseData
{
public int code { get; set; }
public string message { get; set; }
public string sid { get; set; }
public List<Result> data { get; set; }
}
class Result
{
public string src { get; set; }
public string tgt { get; set; }
}
// 讯飞
class XunFeiRequestClass
{
[JsonProperty("common")]
public common c { get; set; }
[JsonProperty("business")]
public business b { get; set; }
[JsonProperty("data")]
public data d { get; set; }
}
class common
{
[JsonProperty("app_id")]
public string app_id { get; set; }
}
class business
{
[JsonProperty("from")]
public string from { get; set; }
[JsonProperty("to")]
public string to { get; set; }
}
class data
{
[JsonProperty("text")]
public string text { get; set; }
}
class HttpUtil//讯飞用
{
//计算字符哈希值
public static string ComputeHash256_base64(string input, HashAlgorithm algorithm)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
return Convert.ToBase64String(hashedBytes);
}
//构建讯飞翻译API的请求参数的JSON字符串
public static string BuildXunFeiRequestJson(string appid, string from, string to, string text)
{
common c = new common();
c.app_id = appid;
business b = new business();
b.from = from;
b.to = to;
data d = new data();
d.text = EncryptBase64(text);
XunFeiRequestClass xunFeiRequestClass = new XunFeiRequestClass();
xunFeiRequestClass.c = c;
xunFeiRequestClass.b = b;
xunFeiRequestClass.d = d;
return JsonConvert.SerializeObject(xunFeiRequestClass);
}
//进行Base64编码
public static string EncryptBase64(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(bytes);
}
//计算字符串的HMAC-SHA256签名
public static string hmacsha256(string text, string secret)
{
string signRet = string.Empty;
using (HMACSHA256 mac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
{
byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(text));
signRet = Convert.ToBase64String(hash);
}
return signRet;
}
//验证服务器证书是否有效
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
}

@ -0,0 +1,65 @@
using System.Diagnostics;
namespace WpfApp1.ScnToJson
{
internal class TranslationScnToJson
{
//private string spath;//scn路径
//private string dpath;//json
private string cmdHandle = "cd " + Directory.GetCurrentDirectory() + "\\VNT\\VNTextPatch";
private string voice = ".\\VNTextPatch extractlocal " + Directory.GetCurrentDirectory() + "\\VNT\\p1 " + Directory.GetCurrentDirectory() + "\\VNT\\p2";
public void StartTrans()
{
this.DirExsis("VNT\\p1");
this.DirExsis("VNT\\p2");
var p = new Process
{
StartInfo =
{
FileName = "PowerShell.exe",
Arguments = "/c " + cmdHandle + "\n" + voice,
UseShellExecute = false,
CreateNoWindow = false,
}
};
p.Start();
p.WaitForExit();
p.Close();
}
public void DirExsis(string id)
{
if(Directory.Exists(Directory.GetCurrentDirectory() + "\\" + id))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\" + id);
}
}
public void StopTrans(string spa, string dps)//自选路径
{
string tempVoice = ".\\VNTextPatch extractlocal " + spa + " " + dps;
var p = new Process
{
StartInfo =
{
FileName = "PowerShell.exe",
Arguments = "/c " + cmdHandle + "\n" + tempVoice,
UseShellExecute = false,
CreateNoWindow = false,
}
};
p.Start();
p.WaitForExit();
p.Close();
}
}
}

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<!-- When using an API key to access Google spreadsheets -->
<add key="GoogleApiKey" value="" />
<!-- Instead of using an API key, you can also use a service account. This way, you don't have to make your spreadsheet public. -->
<!-- To use a service account, download its private key and store it in a file called "google-service-account.json" -->
<add key="MonospaceCharactersPerLine" value="50" />
<add key="ProportionalFontName" value="Franklin Gothic Book" />
<add key="ProportionalFontSize" value="40" />
<add key="ProportionalFontBold" value="false" />
<add key="ProportionalLineWidth" value="1000" />
<add key="SecondaryProportionalLineWidth" value="670" />
</appSettings>
<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>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,2 @@
<?xml version="1.0"?>
<names xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

@ -0,0 +1,7 @@
Excel:
VNTextPatch extractlocal <folder containing original game files> script.xlsx
VNTextPatch insertlocal <folder containing original game files> script.xlsx <folder to receive patched game files>
JSON:
VNTextPatch extractlocal <folder containing original game files> <folder to receive .json files>
VNTextPatch insertlocal <folder containing original game files> <folder containing .json files> <folder to receive patched game files>

@ -0,0 +1,107 @@
using System.Drawing;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
//using System.Windows.Forms;
namespace WpfApp1.WinOcr
{
internal class OcrSofia : Sofia
{
static string path = Directory.GetCurrentDirectory() + "\\TempImage";
public OcrSofia() { }
public string WindowsOcrToGetStringAndTranslate(string name)
{
string retxt = "";
this.DirExists();
//Image image = null;
/*
MODI.Document modiDocument = new MODI.Document();
modiDocument.Create(path + "\\" + name + ".jpg");
modiDocument.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true);
MODI.Image modiImage = (MODI.Image)modiDocument.Images[0];
retxt = modiImage.Layout.Text;
*/
return retxt;
/*
string processName = "notepad"; // 替换为要跟踪的进程名称
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 0)
{
Process process = processes[0];
IntPtr hwnd = process.MainWindowHandle;
var Ocr = new IronTesseract();
OcrResult Result = null;
Ocr.TextAvailable += (s, e) =>
{
Console.WriteLine(e.Text);
Result = e.Result;
};
while (true)
{
if (hwnd != IntPtr.Zero)
{
int length = GetWindowTextLength(hwnd);
if (length > 0)
{
IntPtr buffer = Marshal.AllocHGlobal(length + 1);
GetWindowText(hwnd, buffer, length + 1);
string text = Marshal.PtrToStringAnsi(buffer);
Marshal.FreeHGlobal(buffer);
Ocr.Read(text);
}
}
}
}
else
{
Console.WriteLine("找不到进程:{0}", processName);
}
*/
}
public void DirExists()
{
if(Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/*
internal class OcrSofia : Sofia
{
public OcrSofia() { }
public string WindowsOcrToGetStringAndTranslate()
{
string result = "";
// 获取剪贴板中的图像
Image image = Clipboard.GetImage();
// 将图像保存到临时文件中
string tempFile = Path.GetTempFileName();
image.Save(tempFile, ImageFormat.Tiff);
// 使用Windows OCR引擎识别图像中的文本
MODI.Document modiDocument = new MODI.Document();
modiDocument.Create(tempFile);
modiDocument.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true);
MODI.Image modiImage = (MODI.Image)modiDocument.Images[0];
result = modiImage.Layout.Text;
// 删除临时文件
File.Delete(tempFile);
return result;
}
}
*/
}
}

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.WinOcr
{
internal interface Sofia
{
public abstract string WindowsOcrToGetStringAndTranslate(string name);
}
}

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.translationKey
{
interface TranslationApiStr//Mohammed
{
public abstract List<string> OutputTranslationS(string id);
public abstract List<string> OutputTranslationNameList();
}
interface TranslationApiInt
{
public abstract List<string> OutputTranslationI(int id);
}
}

@ -0,0 +1,61 @@
namespace WpfApp1.translationKey
{
class TranslationPrivateIn
{
private static string pathTemp = Directory.GetCurrentDirectory() + "\\translationResource";
private static string txtPath = Directory.GetCurrentDirectory() + "\\translationResource\\ListPrivate.txt";
public TranslationPrivateIn() { }
public void InPutPrivate(string name, List<string> list)
{
if (Directory.Exists(pathTemp))
{
Directory.CreateDirectory(pathTemp);
}
string temppathTemp = pathTemp + "\\" + name + ".txt";
StreamWriter sw = new StreamWriter(temppathTemp);
StreamWriter sw2 = new StreamWriter(txtPath);
foreach (string s in list)
{
sw.WriteLine(s);
}
sw2.WriteLine(name);
sw.Close();
sw2.Close();
}
public void InputBaiduPrivate(string name, string id, string key)//该函数仅百度支持
{
if(Directory.Exists(pathTemp))
{
Directory.CreateDirectory(pathTemp);
}
string temppathTemp = pathTemp + "\\" + name + ".txt";
StreamWriter sw = new StreamWriter(temppathTemp);
StreamWriter sw2 = new StreamWriter(txtPath);
InputTranslationId(id,sw);
InputTranslationKey(key,sw);
sw2.WriteLine(name);
sw.Close();
sw2.Close();
}
public void InputTranslationId(string id, StreamWriter sw)
{
sw.WriteLine(id);
}
public void InputTranslationKey(string key, StreamWriter sw)
{
sw.WriteLine(key);
}
}
}

@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.translationKey
{
class translationPrivateOut : TranslationApiStr
{
private static string path = Directory.GetCurrentDirectory() + "\\translationResource";
private static string txtPath = Directory.GetCurrentDirectory() + "\\translationResource\\ListPrivate.txt";
private String getTranslationPrivateApi(StreamReader sr)
{
String temp = sr.ReadLine();
if(temp != null)
{
return temp;
}
else
{
return "ERROR";
}
}
private String getTranslationPrivateKey(StreamReader sr)
{
String temp = sr.ReadLine();
if (temp != null)
{
return temp;
}
else
{
return "ERROR";
}
}
public string getpath(string id)
{
return path + "\\" + id + ".txt";
}
public string gettxt()
{
return txtPath;
}
public List<string> OutputTranslationS(string id)
{
string temppath = path + "\\" + id + ".txt";
List<string> temp = new List<string> { };
if (Directory.Exists(temppath))//若不存在
{
temp.Add("尚未输入!!!");
return temp;
}
StreamReader sr = new StreamReader(temppath);
temp.Add(this.getTranslationPrivateApi(sr));
temp.Add(this.getTranslationPrivateKey(sr));
sr.Close();
return temp;
}
public List<string> OutputTranslationNameList()
{
List<string> temp = new List<string> { };
string temptxtpath = txtPath;
if(Directory.Exists(temptxtpath))
{
temp.Add("ERROR");
return temp;
}
StreamReader sr = new StreamReader(temptxtpath);
string temp2 = sr.ReadLine();
if (temp2 == null)
{
temp.Add("ERROR");
}
else
{
while (temp2 != null)
{
temp.Add(temp2);
temp2 = sr.ReadLine();
}
}
sr.Close();
return temp;
}
}
}

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.translationKey
{
class translationPublic : TranslationApiInt
{
public List<string> OutputTranslationI(int id)
{
var temp = new List<string> { };
switch (id)
{
case 0://讯飞
{
temp.Add("1299c840");//id
temp.Add("M2Q4YzkzZTIwZjNkMGE2ZjkwZWMxNzZk");//APISecret
temp.Add("828cb2dc915d28464a904bda5d7b01b3");//APIKey
break;
}
case 1://百度
{
temp.Add("20230923001827495");//APIAppid
temp.Add("yjvMNY33Qc1TYSBjTQYQ");//APIKey
break;
}
case 2://百度2
{
temp.Add("20230925001829663");
temp.Add("f7ZHpw28izQ1VU_ixoY5");
break;
}
case 3://google
{
temp.Add("UNSET!");//NULL,空
temp.Add("UNSET!");//APIKey
break;
}
}
return temp;
}
}
}
Loading…
Cancel
Save