imradv3 / src /WpfEditor /global.cs
fasdfsa's picture
add ComicOcr
7dd6a04
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shapes;
using Path = System.IO.Path;
namespace WpfEditor
{
static class Global
{
/// <summary>
/// 获取图像和JSON文件的路径
/// </summary>
/// <param name="m5">MD5哈希值</param>
/// <returns>包含图像和JSON文件路径的元组</returns>
public static (string ImagePath, string JsonPath) get_img_json_pth(string m5)
{
// 这是工作目录
string pth_img = Path.Combine(Constant.ExecutablePath, "data", "img", $"{m5}.txt"); // .parent_path().parent_path() 在C#中不需要
string pth_json = Path.Combine(Constant.ExecutablePath, "data", "json", $"{m5}.json"); // .parent_path().parent_path() 在C#中不需要
// C#中不需要lexically_normal(),Path.GetFullPath可以规范化路径
pth_img = Path.GetFullPath(pth_img);
pth_json = Path.GetFullPath(pth_json);
// 使用C# 7.0引入的命名元组返回结果
return (ImagePath: pth_img, JsonPath: pth_json);
}
public static (string ImagePath, string JsonPath) get_img_json_pthv2(string pthimg)
{
string m5 = MD5.ComputeFileHash(pthimg);
string dir = Path.GetDirectoryName(pthimg);
string pth_img = Path.Combine(dir, "img", $"{m5}.txt"); // .parent_path().parent_path() 在C#中不需要
string pth_json = Path.Combine(dir, "json", $"{m5}.json"); // .parent_path().parent_path() 在C#中不需要
// C#中不需要lexically_normal(),Path.GetFullPath可以规范化路径
pth_img = Path.GetFullPath(pth_img);
pth_json = Path.GetFullPath(pth_json);
// 使用C# 7.0引入的命名元组返回结果
return (ImagePath: pth_img, JsonPath: pth_json);
}
// 阿里 ocr的 JSON 需要添加 guid
public static JObject set_guid_md5(JObject jsn, string md5)
{
int width = jsn.Value<int>("width");
int height = jsn.Value<int>("height");
var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
foreach (var item in prism_wordsInfo)
{
JArray charInfo = item["charInfo"].Value<JArray>();
string line_word = item["word"].Value<string>();
int angle = item["angle"].Value<int>();
JArray pos = item["pos"].Value<JArray>();
JObject lu = (JObject)pos[0];
JObject ru = (JObject)pos[1];
JObject rd = (JObject)pos[2];
JObject ld = (JObject)pos[3];
foreach (var item2 in charInfo)
{
string oneChar = item2["word"].Value<string>();
item2["guid"] = Guid.NewGuid().ToString();
item2["isDeleted"] = 0;
item2["ImageMD5"] = md5;
if (angle == -90)
{
// x, y 互换
int x = item2["y"].Value<int>();
int y = item2["x"].Value<int>();
int w = item2["h"].Value<int>();
int h = item2["w"].Value<int>();
x = lu["x"].Value<int> ()+ x;
y = lu["y"].Value<int>() + y;
item2["x"] = x;
item2["y"] = y;
item2["w"] = w;
item2["h"] = h;
}
}
}
return jsn;
}
// 删掉 jsn 里不在选区的文字
public static JObject find_rectange_text(JObject jsn, int lft, int tp, int wdth, int hght, int Id ) // 矩形框 ID,从 1 开始递增
{
//_lines.Add(new TextLine());
int width = jsn.Value<int>("width");
int height = jsn.Value<int>("height");
JObject jsn_new = new JObject();
JArray prism_wordsInfo_new = new JArray();
jsn_new["width"] = width;
jsn_new["height"] = height;
jsn_new["prism_wordsInfo"] = prism_wordsInfo_new;
var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
foreach (var item in prism_wordsInfo)
{
JArray charInfo = item["charInfo"].Value<JArray>();
string line_word = item["word"].Value<string>();
//int angle = item["angle"].Value<int>();
JArray pos = item["pos"].Value<JArray>();
JObject lu = (JObject)pos[0];
JObject ru = (JObject)pos[1];
JObject rd = (JObject)pos[2];
JObject ld = (JObject)pos[3];
// 先看行文字上下是否在选区内
int line_top = Math.Min(lu["y"].Value<int>(), ru["y"].Value<int>());
int line_bottom = Math.Max(ld["y"].Value<int>(), rd["y"].Value<int>());
if (line_top > tp + hght || line_bottom < tp)
{
// 整行文字不在选区内
continue;
}
// 实际上要生成选区内的新 jsn
// 下面要生成很多新行,行内的很多符等
JObject line_new = new JObject();
string line_word_new = "";
JArray pos_new = new JArray();
JArray charInfo_new = new JArray();
line_new["word"] = "";
line_new["pos"] = pos_new;
line_new["charInfo"] = charInfo_new;
JObject selected_rectange = new JObject { { "Id", Id }, { "lft", lft }, { "tp", tp }, { "wdth", wdth }, { "hght", hght } }; // 框选矩形
line_new["selected_rectange"] = selected_rectange;
prism_wordsInfo_new.Add(line_new);
// 再看列文字左右是否在选区内
foreach (var item2 in charInfo)
{
string oneChar = item2["word"].Value<string>();
int x = item2["x"].Value<int>();
int y = item2["y"].Value<int>();
int w = item2["h"].Value<int>();
int h = item2["w"].Value<int>();
if ( x >= lft && (x + w <= lft + wdth) )
{
line_word_new += oneChar;
// 这个字在选区内
charInfo_new.Add(item2.DeepClone());
}
}
if (charInfo_new.Count > 0)
{
line_new["word"] = line_word_new;
var first = charInfo_new[0];
var last = charInfo_new[charInfo_new.Count - 1];
int min_left = first["x"].Value<int>(); // Math.Min
int max_right = last["x"].Value<int>() + last["w"].Value<int>(); // Math.Max
int min_top = Math.Min(first["y"].Value<int>(), last["y"].Value<int>());
int max_top = Math.Max(first["y"].Value<int>() + first["h"].Value<int>(), last["y"].Value<int>() + last["h"].Value<int>());
JObject lu_pos = new JObject
{
["x"] = min_left,
["y"] = min_top
};
JObject ru_pos = new JObject
{
["x"] = max_right,
["y"] = min_top
};
JObject rd_pos = new JObject
{
["x"] = max_right,
["y"] = max_top
};
JObject ld_pos = new JObject
{
["x"] = min_left,
["y"] = max_top
};
pos_new.Add(lu_pos);
pos_new.Add(ru_pos);
pos_new.Add(rd_pos);
pos_new.Add(ld_pos);
}
}
if (prism_wordsInfo_new.Count > 0)
{
//jsn["prism_wordsInfo"] = prism_wordsInfo_new;
}
else
{
// 如果没有文字在选区内
jsn_new = null;
}
return jsn_new;
}
public static async Task<Tuple<JObject, string, string, string>> img_md5_jsn(string pthimg, OcrMode ocrEngine = OcrMode.WeChatOcr, bool doOcr=true)
{
string m5 = MD5.ComputeFileHash(pthimg);
var (pth_img, pth_json) = Global.get_img_json_pthv2(pthimg);
if (!Path.Exists(pth_json) || !Path.Exists(pth_img))
{
if (!doOcr)
{
return new Tuple<JObject, string, string, string>(null, m5, pth_img, pth_json);
}
string result = "";
if (ocrEngine == OcrMode.WeChatOcr)
{
result = WeChatOcr.RecognizeImage(pthimg);
}
else if (ocrEngine == OcrMode.ComicOcr)
{
result = await ComicOcr.RecognizeImage(pthimg);
}
else if (ocrEngine == OcrMode.AliOCR)
{
result = await AliOcr.RecognizeImage(pthimg);
}
else if (ocrEngine == OcrMode.PPOCR)
{
}
try
{
JObject.Parse(result);
} catch(Exception ex)
{
throw ex;
}
string b64_str = Base64.Base64Encode(pthimg);
DirectoryInfo di = Directory.CreateDirectory( Path.GetDirectoryName(pth_json) );
DirectoryInfo di2 = Directory.CreateDirectory(Path.GetDirectoryName(pth_img) );
using (FileStream fs = new FileStream(pth_json, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(result);
fs.Write(bytes, 0, bytes.Length);
}
using (FileStream fs = new FileStream(pth_img, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(b64_str);
fs.Write(bytes, 0, bytes.Length);
}
// 应用程序退出时释放资源
//WeChatOcr.FreeDll();
if (!Path.Exists(pth_json) || !Path.Exists(pth_img))
{
MessageBox.Show("不存在 json 或 image", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return null;
}
}
var jsonstr = File.ReadAllText(pth_json, new System.Text.UTF8Encoding(false));
JObject jsn = null;
try
{
jsn = JObject.Parse(jsonstr);
}
catch (Exception ex)
{
MessageBox.Show("json 解析失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return null;
}
if (!jsonstr.Contains("guid"))
{
// 可能是阿里云的OCR结果,没有guid (坚排的坐标对不上)
jsn = Global.set_guid_md5(jsn, m5);
string jsn_str = jsn.ToString(Formatting.Indented).Replace("\r\n", "\n");
File.WriteAllText(pth_json, jsn_str);
}
return new Tuple<JObject, string, string, string>(jsn, m5, pth_img, pth_json);
}
public static void saveJsonReviseEdit(string pth_json, List<TextLine> lines)
{
var dir = Path.GetDirectoryName(Path.GetDirectoryName(pth_json));
var name_json = Path.GetFileName(pth_json);
var dir_new = Path.Combine(dir, "json2");
Directory.CreateDirectory(dir_new);
var pth_json_reviseEdit = Path.Combine(dir_new, name_json);
// 使用 Newtonsoft.Json 将 lines 转换为 JSON 并保存
try
{
// 配置 JSON 序列化设置,忽略 Brush 等不可序列化的属性
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
string jsonString = JsonConvert.SerializeObject(lines, settings);
//List<TextLine> lines2 = loadJsonReviseEdit_(jsonString);
File.WriteAllText(pth_json_reviseEdit, jsonString, Encoding.UTF8);
}
catch (Exception ex)
{
throw new Exception($"保存 JSON 文件失败: {ex.Message}", ex);
}
}
public static List<TextLine> loadJsonReviseEdit_(string jsonString)
{
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
List<TextLine> lines = JsonConvert.DeserializeObject<List<TextLine>>(jsonString, settings);
// 确保返回的不是 null,并重新初始化 Brush 属性
if (lines != null)
{
foreach (var line in lines)
{
foreach (var character in line.Characters)
{
if (character.Foreground == null)
character.Foreground = System.Windows.Media.Brushes.Black;
}
}
}
return lines ?? new List<TextLine>();
}
catch (Exception ex)
{
throw new Exception($"反序列化 JSON 失败: {ex.Message}", ex);
}
}
// 从 JSON 恢复 lines 的方法
public static List<TextLine> loadJsonReviseEdit(string pth_json_reviseEdit)
{
try
{
if (!File.Exists(pth_json_reviseEdit))
{
//throw new FileNotFoundException($"JSON 文件不存在: {pth_json_reviseEdit}");
return new List<TextLine>();
}
string jsonString = File.ReadAllText(pth_json_reviseEdit, Encoding.UTF8);
return loadJsonReviseEdit_(jsonString);
//var settings = new JsonSerializerSettings
//{
// NullValueHandling = NullValueHandling.Ignore,
// DefaultValueHandling = DefaultValueHandling.Ignore
//};
//List<TextLine> lines = JsonConvert.DeserializeObject<List<TextLine>>(jsonString, settings);
//// 确保返回的不是 null,并重新初始化 Brush 属性
//if (lines != null)
//{
// foreach (var line in lines)
// {
// foreach (var character in line.Characters)
// {
// if (character.Foreground == null)
// character.Foreground = System.Windows.Media.Brushes.Black;
// }
// }
//}
//return lines ?? new List<TextLine>();
}
catch (Exception ex)
{
throw new Exception($"加载 JSON 文件失败: {ex.Message}", ex);
}
}
public static string get_json2_path(string pth_json)
{
var dir = Path.GetDirectoryName(Path.GetDirectoryName(pth_json));
var name_json = Path.GetFileName(pth_json);
var dir_new = Path.Combine(dir, "json2");
var pth_json_reviseEdit = Path.Combine(dir_new, name_json);
return pth_json_reviseEdit;
}
// 重载方法:根据原始 JSON 路径自动构建 reviseEdit JSON 路径
public static List<TextLine> loadJsonReviseEdit_FromOriginalPath(string pth_json)
{
//var dir = Path.GetDirectoryName(Path.GetDirectoryName(pth_json));
//var name_json = Path.GetFileName(pth_json);
//var dir_new = Path.Combine(dir, "json2");
//var pth_json_reviseEdit = Path.Combine(dir_new, name_json);
var pth_json_reviseEdit = get_json2_path(pth_json);
return loadJsonReviseEdit(pth_json_reviseEdit);
}
}
}