317 lines
12 KiB
C#
317 lines
12 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
namespace DwgExtractorManual.Models
|
|
{
|
|
/// <summary>
|
|
/// JSON 파일 처리 및 매핑 데이터 관리를 담당하는 클래스
|
|
/// </summary>
|
|
internal class JsonDataProcessor
|
|
{
|
|
/// <summary>
|
|
/// JSON 파일에서 PDF 분석 결과를 읽어 매핑 데이터를 업데이트
|
|
/// </summary>
|
|
public bool UpdateMappingDataFromJson(Dictionary<string, Dictionary<string, (string, string, string, string)>> mappingData, string jsonFilePath)
|
|
{
|
|
try
|
|
{
|
|
Debug.WriteLine($"[DEBUG] JSON 파일에서 PDF 값 업데이트 시작: {jsonFilePath}");
|
|
|
|
if (!File.Exists(jsonFilePath))
|
|
{
|
|
Debug.WriteLine($"? JSON 파일이 존재하지 않습니다: {jsonFilePath}");
|
|
return false;
|
|
}
|
|
|
|
// JSON 파일 읽기 및 정리
|
|
string jsonContent = File.ReadAllText(jsonFilePath, System.Text.Encoding.UTF8);
|
|
jsonContent = CleanJsonContent(jsonContent);
|
|
|
|
JObject jsonData;
|
|
try
|
|
{
|
|
jsonData = JObject.Parse(jsonContent);
|
|
}
|
|
catch (Newtonsoft.Json.JsonReaderException jsonEx)
|
|
{
|
|
Debug.WriteLine($"? JSON 파싱 오류: {jsonEx.Message}");
|
|
throw new System.Exception($"PDF 분석 JSON 파일 파싱 실패: {jsonEx.Message}\n파일: {jsonFilePath}");
|
|
}
|
|
|
|
var results = jsonData["results"] as JArray;
|
|
if (results == null)
|
|
{
|
|
Debug.WriteLine("? JSON에서 'results' 배열을 찾을 수 없습니다.");
|
|
return false;
|
|
}
|
|
|
|
int updatedCount = 0;
|
|
int totalEntries = 0;
|
|
|
|
foreach (JObject result in results)
|
|
{
|
|
var fileInfo = result["file_info"];
|
|
var pdfAnalysis = result["pdf_analysis"];
|
|
|
|
if (fileInfo == null || pdfAnalysis == null) continue;
|
|
|
|
string fileName = fileInfo["name"]?.ToString();
|
|
if (string.IsNullOrEmpty(fileName)) continue;
|
|
|
|
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
|
|
|
|
if (!mappingData.ContainsKey(fileNameWithoutExt))
|
|
{
|
|
Debug.WriteLine($"?? 매핑 데이터에 파일이 없습니다: {fileNameWithoutExt}");
|
|
continue;
|
|
}
|
|
|
|
foreach (var property in pdfAnalysis.Cast<JProperty>())
|
|
{
|
|
string aiLabel = property.Name;
|
|
var valueObj = property.Value as JObject;
|
|
|
|
if (valueObj == null) continue;
|
|
|
|
string pdfValue = valueObj["value"]?.ToString();
|
|
if (string.IsNullOrEmpty(pdfValue)) continue;
|
|
|
|
totalEntries++;
|
|
|
|
var fileData = mappingData[fileNameWithoutExt];
|
|
var matchingEntry = fileData.FirstOrDefault(kvp =>
|
|
string.Equals(kvp.Value.Item1.Trim(), aiLabel.Trim(), StringComparison.OrdinalIgnoreCase));
|
|
|
|
if (!string.IsNullOrEmpty(matchingEntry.Key))
|
|
{
|
|
var existingValue = matchingEntry.Value;
|
|
fileData[matchingEntry.Key] = (existingValue.Item1, existingValue.Item2, existingValue.Item3, pdfValue);
|
|
updatedCount++;
|
|
}
|
|
}
|
|
}
|
|
|
|
Debug.WriteLine($"[DEBUG] PDF 데이터 업데이트 완료: {updatedCount}/{totalEntries} 업데이트됨");
|
|
return true;
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"? JSON에서 PDF 값 업데이트 중 오류: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 매핑 딕셔너리를 JSON 파일로 저장
|
|
/// </summary>
|
|
public void SaveMappingDictionary(Dictionary<string, Dictionary<string, (string, string, string, string)>> mappingData, string filePath)
|
|
{
|
|
try
|
|
{
|
|
Debug.WriteLine($"[DEBUG] 매핑 딕셔너리 저장 시작: {filePath}");
|
|
|
|
var serializableData = new Dictionary<string, Dictionary<string, object>>();
|
|
|
|
foreach (var fileEntry in mappingData)
|
|
{
|
|
var fileData = new Dictionary<string, object>();
|
|
foreach (var mapEntry in fileEntry.Value)
|
|
{
|
|
fileData[mapEntry.Key] = new
|
|
{
|
|
AILabel = mapEntry.Value.Item1,
|
|
DwgTag = mapEntry.Value.Item2,
|
|
DwgValue = mapEntry.Value.Item3,
|
|
PdfValue = mapEntry.Value.Item4
|
|
};
|
|
}
|
|
serializableData[fileEntry.Key] = fileData;
|
|
}
|
|
|
|
string jsonContent = JsonConvert.SerializeObject(serializableData, Formatting.Indented);
|
|
File.WriteAllText(filePath, jsonContent, System.Text.Encoding.UTF8);
|
|
|
|
Debug.WriteLine($"? 매핑 딕셔너리 저장 완료: {Path.GetFileName(filePath)}");
|
|
Debug.WriteLine($"?? 저장된 파일 수: {mappingData.Count}");
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"? 매핑 딕셔너리 저장 중 오류: {ex.Message}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON 파일에서 매핑 딕셔너리를 로드
|
|
/// </summary>
|
|
public Dictionary<string, Dictionary<string, (string, string, string, string)>> LoadMappingDictionary(string filePath)
|
|
{
|
|
var result = new Dictionary<string, Dictionary<string, (string, string, string, string)>>();
|
|
|
|
try
|
|
{
|
|
Debug.WriteLine($"[DEBUG] 매핑 딕셔너리 로드 시작: {filePath}");
|
|
|
|
if (!File.Exists(filePath))
|
|
{
|
|
Debug.WriteLine($"?? 매핑 파일이 존재하지 않습니다: {filePath}");
|
|
return result;
|
|
}
|
|
|
|
string jsonContent = File.ReadAllText(filePath, System.Text.Encoding.UTF8);
|
|
jsonContent = CleanJsonContent(jsonContent);
|
|
|
|
Dictionary<string, Dictionary<string, JObject>> deserializedData;
|
|
try
|
|
{
|
|
deserializedData = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, JObject>>>(jsonContent);
|
|
}
|
|
catch (Newtonsoft.Json.JsonReaderException jsonEx)
|
|
{
|
|
Debug.WriteLine($"? JSON 파싱 오류: {jsonEx.Message}");
|
|
throw new System.Exception($"매핑 JSON 파일 파싱 실패: {jsonEx.Message}\n파일: {filePath}");
|
|
}
|
|
|
|
if (deserializedData != null)
|
|
{
|
|
foreach (var fileEntry in deserializedData)
|
|
{
|
|
var fileData = new Dictionary<string, (string, string, string, string)>();
|
|
|
|
foreach (var mapEntry in fileEntry.Value)
|
|
{
|
|
var valueObj = mapEntry.Value;
|
|
string aiLabel = valueObj["AILabel"]?.ToString() ?? "";
|
|
string dwgTag = valueObj["DwgTag"]?.ToString() ?? "";
|
|
string dwgValue = valueObj["DwgValue"]?.ToString() ?? "";
|
|
string pdfValue = valueObj["PdfValue"]?.ToString() ?? "";
|
|
|
|
fileData[mapEntry.Key] = (aiLabel, dwgTag, dwgValue, pdfValue);
|
|
}
|
|
|
|
result[fileEntry.Key] = fileData;
|
|
}
|
|
}
|
|
|
|
Debug.WriteLine($"? 매핑 딕셔너리 로드 완료");
|
|
Debug.WriteLine($"?? 로드된 파일 수: {result.Count}");
|
|
|
|
return result;
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"? 매핑 딕셔너리 로드 중 오류: {ex.Message}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON 내용을 정리하여 파싱 가능한 상태로 만듭니다.
|
|
/// </summary>
|
|
private string CleanJsonContent(string jsonContent)
|
|
{
|
|
if (string.IsNullOrEmpty(jsonContent))
|
|
return jsonContent;
|
|
|
|
try
|
|
{
|
|
var lines = jsonContent.Split('\n');
|
|
var cleanedLines = new List<string>();
|
|
bool inMultiLineComment = false;
|
|
|
|
foreach (string line in lines)
|
|
{
|
|
string processedLine = line;
|
|
|
|
// 멀티라인 주석 처리
|
|
if (inMultiLineComment)
|
|
{
|
|
int endIndex = processedLine.IndexOf("*/");
|
|
if (endIndex >= 0)
|
|
{
|
|
processedLine = processedLine.Substring(endIndex + 2);
|
|
inMultiLineComment = false;
|
|
}
|
|
else
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
|
|
int multiLineStart = processedLine.IndexOf("/*");
|
|
if (multiLineStart >= 0)
|
|
{
|
|
int multiLineEnd = processedLine.IndexOf("*/", multiLineStart + 2);
|
|
if (multiLineEnd >= 0)
|
|
{
|
|
processedLine = processedLine.Substring(0, multiLineStart) +
|
|
processedLine.Substring(multiLineEnd + 2);
|
|
}
|
|
else
|
|
{
|
|
processedLine = processedLine.Substring(0, multiLineStart);
|
|
inMultiLineComment = true;
|
|
}
|
|
}
|
|
|
|
// 싱글라인 주석 제거
|
|
bool inString = false;
|
|
bool escaped = false;
|
|
int commentIndex = -1;
|
|
|
|
for (int i = 0; i < processedLine.Length - 1; i++)
|
|
{
|
|
char current = processedLine[i];
|
|
char next = processedLine[i + 1];
|
|
|
|
if (escaped)
|
|
{
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
|
|
if (current == '\\')
|
|
{
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
|
|
if (current == '"')
|
|
{
|
|
inString = !inString;
|
|
continue;
|
|
}
|
|
|
|
if (!inString && current == '/' && next == '/')
|
|
{
|
|
commentIndex = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (commentIndex >= 0)
|
|
{
|
|
processedLine = processedLine.Substring(0, commentIndex);
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(processedLine))
|
|
{
|
|
cleanedLines.Add(processedLine);
|
|
}
|
|
}
|
|
|
|
return string.Join("\n", cleanedLines);
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"? JSON 정리 중 오류: {ex.Message}");
|
|
return jsonContent;
|
|
}
|
|
}
|
|
}
|
|
} |