增加了知识图谱导出excel

This commit is contained in:
chentianrui
2025-08-18 15:14:37 +08:00
parent ce2986fbe2
commit 3fd0b2af0c
610 changed files with 6062 additions and 4932473 deletions
+216 -300
View File
@@ -1,352 +1,268 @@
"""
第一步:将工程文件转化为json文件
"""
import os
import shutil
import subprocess
import time
from gradio_client import file
import requests
import urllib.parse
import json
import sys
import shutil
import threading
import glob
import atexit
import tempfile
import uuid
# 全局变量,用于跟踪Java进程
# ==================== 配置区 ====================
JAVA_WORKING_DIR = "D:/eclipseworkspace/bwyAnalysis2.3.2/analysis-server"
JAR_NAME = "booway-analysis-server-null.jar"
SERVER_URL = "http://localhost:8090/api/doAnalysis"
# ==============================================
# 全局变量:Java 进程
java_process = None
def convert_project_to_json(input_folder, output_folder):
"""
将指定文件夹中的工程文件转换为JSON格式,并保存到输出文件夹
参数:
input_folder: 输入文件夹路径,包含要转换的工程文件
output_folder: 输出文件夹路径,转换后的JSON文件将保存在这里
返回:
转换成功的文件列表,格式为 [(源文件路径, 生成的JSON文件路径), ...]
"""
# 确保输入和输出文件夹存在
if not os.path.exists(input_folder):
print(f"错误:输入文件夹 {input_folder} 不存在")
return []
os.makedirs(output_folder, exist_ok=True)
# 启动Java服务
if not start_java_server():
print("错误:无法启动Java服务")
return []
# 查找输入文件夹中的所有文件(不限制格式)
project_files = []
for file in os.listdir(input_folder):
file_path = os.path.join(input_folder, file)
# 只处理文件,不处理文件夹
if os.path.isfile(file_path):
project_files.append(file_path)
if not project_files:
print(f"警告:在文件夹 {input_folder} 中没有找到任何文件")
return []
print(f"找到 {len(project_files)} 个文件: {[os.path.basename(f) for f in project_files]}")
# 转换每个文件
successful_conversions = []
for file_path in project_files:
print(f"正在处理文件: {file_path}")
result_message, json_file_path = process_file(file_path, output_folder)
if json_file_path:
print(f"转换成功: {os.path.basename(file_path)} -> {os.path.basename(json_file_path)}")
successful_conversions.append((file_path, json_file_path))
else:
print(f"转换失败: {os.path.basename(file_path)} - {result_message}")
# 返回转换结果
return successful_conversions
def start_java_server():
"""启动Java服务器,返回是否成功启动"""
"""启动 Java 服务"""
global java_process
if java_process is not None:
# 如果进程已存在,检查是否在运行
if java_process.poll() is None: # None表示进程仍在运行
return True
# 使用相对路径
script_dir = os.path.dirname(os.path.abspath(__file__))
working_dir = os.path.join(script_dir, "analysis-server")
# 确保工作目录存在
if not os.path.exists(working_dir):
print(f"错误:工作目录不存在: {working_dir}")
return False
# 移除不必要的config目录创建
# config_dir = os.path.join(script_dir, "config")
# if not os.path.exists(config_dir):
# os.makedirs(config_dir, exist_ok=True)
# print(f"创建配置目录: {config_dir}")
if java_process is not None and java_process.poll() is None:
print("✅ Java 服务已在运行。")
return True
try:
# 使用与原始Java命令相同的方式启动
jar_path = os.path.join(JAVA_WORKING_DIR, JAR_NAME)
if not os.path.exists(jar_path):
print(f"❌ JAR 文件不存在: {jar_path}")
return False
if not os.path.exists(JAVA_WORKING_DIR):
print(f"❌ Java 工作目录不存在: {JAVA_WORKING_DIR}")
return False
print(f"📁 启动 Java 服务: {jar_path}")
cmd = ["java", "-Dfile.encoding=UTF-8", "-jar", JAR_NAME]
java_process = subprocess.Popen(
["java", "-Dfile.encoding=UTF-8", "-jar", "booway-analysis-server-null.jar"], # 使用相对路径
cwd=working_dir, # 在正确的工作目录中运行
cmd,
cwd=JAVA_WORKING_DIR,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
encoding="utf-8",
errors="replace",
)
# 实时打印日志但不发送到前端
def read_output(stream, is_error=False):
for line in iter(stream.readline, ""):
stripped_line = line.strip()
if stripped_line:
print(stripped_line)
def log_output(pipe, prefix):
for line in iter(pipe.readline, ""):
if line.strip():
print(f"{prefix}{line.strip()}")
t1 = threading.Thread(target=read_output, args=(java_process.stdout,), daemon=True)
t2 = threading.Thread(target=read_output, args=(java_process.stderr, True), daemon=True)
t1.start()
t2.start()
# 等待服务启动
print("等待Java服务启动...")
time.sleep(20) # 等待20秒
threading.Thread(target=log_output, args=(java_process.stdout, "【OUT】 "), daemon=True).start()
threading.Thread(target=log_output, args=(java_process.stderr, "【ERR】 "), daemon=True).start()
print("⏳ 等待服务启动(等待 20 秒)...")
time.sleep(20)
return True
except Exception as e:
print(f"启动Java服务失败: {str(e)}")
print(f"启动 Java 服务失败: {e}")
return False
def process_file(file_path, output_folder):
"""处理单个工程文件,返回结果消息和JSON文件路径"""
try:
# 创建临时工作目录
temp_dir = tempfile.mkdtemp(prefix="project_converter_")
print(f"创建临时工作目录: {temp_dir}")
# 复制工程文件到临时目录
file_name = os.path.basename(file_path)
temp_file_path = os.path.join(temp_dir, file_name)
shutil.copy2(file_path, temp_file_path)
print(f"复制文件到临时目录: {file_path} -> {temp_file_path}")
def check_server_ready(timeout=30):
"""检查服务是否可用"""
print("🔍 检测服务是否就绪...")
start_time = time.time()
while time.time() - start_time < timeout:
try:
# 调用Java服务处理文件
absolute_temp_dir = os.path.abspath(temp_dir).replace("\\", "/")
encoded_temp_dir = urllib.parse.quote(absolute_temp_dir)
requests.get("http://localhost:8090/", timeout=3)
print("✅ 服务已就绪!")
return True
except:
time.sleep(1)
print("❌ 服务启动超时。")
return False
url = f"http://localhost:8090/api/doAnalysis?filePath={encoded_temp_dir}"
print("正在请求:", url)
print(f"临时目录路径: {absolute_temp_dir}")
print(f"文件名: {file_name}")
# 记录转换前文件夹状态
before_files = set(os.listdir(temp_dir))
print(f"转换前临时目录内容: {before_files}")
def convert_json_to_readable(input_file, output_file=None):
"""
将JSON文件转换为可读格式并保存
# 发送请求到Java服务
response = requests.get(url, timeout=180)
print(f"API响应状态码: {response.status_code}")
print(f"API响应内容: {response.text[:200]}...")
参数:
input_file: 输入JSON文件路径
output_file: 输出文件路径,如果为None则自动生成
"""
try:
with open(input_file, "r", encoding="utf-8") as f:
data = json.load(f)
# 等待一段时间,确保JSON文件已生成
time.sleep(10) # 等待10秒
if output_file is None:
base_name = os.path.splitext(input_file)[0]
output_file = f"{base_name}.json"
# 记录转换后文件夹状态
after_files = set(os.listdir(temp_dir))
print(f"转换后临时目录内容: {after_files}")
# 找出新增文件
new_files = after_files - before_files
print(f"新增文件: {new_files}")
# 查找生成的JSON文件
json_files = [f for f in new_files if f.endswith(".json")]
if not json_files:
# 如果没有找到新增的JSON文件,查找所有JSON文件
json_files = [f for f in after_files if f.endswith(".json")]
if json_files:
# 按修改时间排序,获取最新的
json_file = max(json_files, key=lambda f: os.path.getmtime(os.path.join(temp_dir, f)))
temp_json_path = os.path.join(temp_dir, json_file)
# 确保JSON文件是UTF-8编码
with open(temp_json_path, "r", encoding="utf-8") as f:
data = json.load(f)
# 生成输出文件名
base_name = os.path.splitext(file_name)[0]
output_json_name = f"{base_name}.json"
output_json_path = os.path.join(output_folder, output_json_name)
# 检查是否已存在同名文件,如果存在,添加时间戳
if os.path.exists(output_json_path):
timestamp = int(time.time())
output_json_name = f"{base_name}_{timestamp}.json"
output_json_path = os.path.join(output_folder, output_json_name)
# 将JSON数据写入输出文件
with open(output_json_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"JSON文件已保存到: {output_json_path}")
return "✅ 工程文件转换成功!", output_json_path
else:
print("未能在临时目录中找到JSON文件,开始搜索其他可能的位置...")
# 搜索多个可能的位置
search_locations = [
temp_dir, # 临时目录
os.path.join(
os.path.dirname(os.path.abspath(__file__)), "analysis-server"
), # 相对路径的analysis-server
os.getcwd(), # 当前工作目录
os.path.expanduser("~"), # 用户主目录
os.path.join(os.path.expanduser("~"), "Desktop"), # 桌面目录
os.path.join(os.path.expanduser("~"), "Documents"), # 文档目录
]
# 添加Java服务的工作目录
java_working_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "analysis-server")
if os.path.exists(java_working_dir):
search_locations.append(java_working_dir)
# 搜索所有位置
found_json_files = []
for search_dir in search_locations:
if os.path.exists(search_dir):
print(f"搜索目录: {search_dir}")
try:
json_files_in_dir = [f for f in os.listdir(search_dir) if f.endswith(".json")]
if json_files_in_dir:
# 按修改时间排序,获取最新的
latest_json = max(
json_files_in_dir, key=lambda f: os.path.getmtime(os.path.join(search_dir, f))
)
json_path = os.path.join(search_dir, latest_json)
found_json_files.append((json_path, os.path.getmtime(json_path)))
print(f"{search_dir} 中找到JSON文件: {latest_json}")
except Exception as e:
print(f"搜索目录 {search_dir} 时出错: {e}")
if found_json_files:
# 选择最新的JSON文件
latest_json_path, _ = max(found_json_files, key=lambda x: x[1])
# 生成输出文件名
base_name = os.path.splitext(file_name)[0]
output_json_name = f"{base_name}.json"
output_json_path = os.path.join(output_folder, output_json_name)
# 检查是否已存在同名文件,如果存在,添加时间戳
if os.path.exists(output_json_path):
timestamp = int(time.time())
output_json_name = f"{base_name}_{timestamp}.json"
output_json_path = os.path.join(output_folder, output_json_name)
# 读取JSON文件并保存到输出目录
with open(latest_json_path, "r", encoding="utf-8") as f:
data = json.load(f)
with open(output_json_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"{latest_json_path} 复制JSON文件到: {output_json_path}")
return "✅ 工程文件转换成功!", output_json_path
else:
print("在所有搜索位置中都未找到JSON文件")
return "❌ 转换可能已完成,但未能找到JSON文件。", None
finally:
# 清理临时目录
try:
shutil.rmtree(temp_dir)
print(f"已清理临时目录: {temp_dir}")
except Exception as e:
print(f"清理临时目录时出错: {str(e)}")
with open(output_file, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"✅ JSON美化成功: {output_file}")
return output_file
except Exception as e:
print(f"处理文件时发生错误: {str(e)}")
return f"❌ 发生错误:{str(e)}", None
print(f"❌ 转换JSON失败 {input_file}: {e}")
return None
def convert_project_to_json(input_folder, output_folder):
"""
将工程文件夹转换为JSON,并移动到输出文件夹(含美化)
参数:
input_folder: 工程文件所在目录(包含 .zwzj 文件)
output_folder: 转换后的 JSON 文件输出目录
返回:
tuple(bool, int): (是否成功, 成功转移并美化的文件数量)
"""
transferred_count = 0 # 记录成功转移的文件数
success = False # 整体是否成功
# --- 路径预处理 ---
try:
input_folder = os.path.abspath(input_folder)
output_folder = os.path.abspath(output_folder)
except Exception as e:
print(f"❌ 路径解析失败: {e}")
return False, 0
print(f"📁 输入工程目录: {input_folder}")
print(f"📁 输出 JSON 目录: {output_folder}")
# -----------------
# 1. 检查输入目录
if not os.path.exists(input_folder):
print(f"❌ 输入目录不存在: {input_folder}")
return False, 0
if not os.path.isdir(input_folder):
print(f"❌ 输入路径不是目录: {input_folder}")
return False, 0
# 2. 确保输出目录存在
try:
os.makedirs(output_folder, exist_ok=True)
output_folder = os.path.abspath(output_folder)
except Exception as e:
print(f"❌ 创建输出目录失败: {e}")
return False, 0
# 3. 启动 Java 服务
if not start_java_server():
return False, 0
if not check_server_ready():
return False, 0
# 4. 调用 API 开始分析
params = {"filePath": input_folder.replace("\\", "/")}
print(f"🌐 调用 API: {SERVER_URL}?{requests.compat.urlencode(params)}")
try:
response = requests.get(SERVER_URL, params=params, timeout=180)
print(f"📡 响应状态码: {response.status_code}")
if response.status_code != 200:
print(f"❌ API 调用失败: {response.text}")
return False, 0
result = response.json()
if not result.get("success", False):
print(f"❌ 服务返回失败: {result.get('msg', '未知错误')}")
return False, 0
except Exception as e:
print(f"❌ 调用 API 出错: {e}")
return False, 0
# 5. 等待并检测 JSON 文件生成完成(改进版)
print("⏳ 正在等待 JSON 文件生成完成...")
json_files = []
max_wait_time = 600
check_interval = 2
start_time = time.time()
while time.time() - start_time < max_wait_time:
# 获取目录中的所有文件
all_files = os.listdir(input_folder)
# 获取JSON文件列表
current_jsons = [f for f in all_files if f.endswith(".json")]
# 获取非JSON文件列表
non_json_files = [f for f in all_files if not f.endswith(".json")]
# 计算文件数量
json_count = len(current_jsons)
non_json_count = len(non_json_files)
print(
f" ├─ 第 {int(time.time()-start_time)} 秒: 发现 {json_count} 个 JSON 文件, {non_json_count} 个非 JSON 文件"
)
# 如果JSON文件和非JSON文件数量相等且都大于0,认为处理完成
if json_count > 0 and json_count == non_json_count:
json_files = current_jsons
print(f"✅ 文件生成完成,JSON文件和非JSON文件数量相等(各{json_count}个)。")
break
time.sleep(check_interval)
else:
json_files = [f for f in os.listdir(input_folder) if f.endswith(".json")]
if json_files:
print(f"⚠️ 警告:等待超时,但已发现 {len(json_files)} 个 JSON 文件,继续处理。")
else:
print(f"❌ 在 {max_wait_time} 秒内未生成任何 JSON 文件。")
return False, 0
# 6. 查找所有 .json 文件
json_files = [f for f in os.listdir(input_folder) if f.endswith(".json")]
if not json_files:
print(f"❌ 未在 {input_folder} 中生成 JSON 文件。")
return False, 0
print(f"📄 发现 {len(json_files)} 个 JSON 文件: {json_files}")
# 7. 转换为可读格式并移动到输出目录
transferred_count = 0
for file_name in json_files:
src_path = os.path.join(input_folder, file_name)
readable_path = os.path.join(output_folder, f"{os.path.splitext(file_name)[0]}.json")
if convert_json_to_readable(src_path, readable_path):
transferred_count += 1
else:
print(f"⚠️ 跳过文件: {file_name}")
print(f"✅ 共转移并美化 {transferred_count}/{len(json_files)} 个 JSON 文件到: {output_folder}")
# ✅ 返回成功状态和实际转移数量
success = True
return success, transferred_count
def cleanup():
"""清理资源,关闭Java进程"""
"""清理 Java 进程"""
global java_process
if java_process is not None and java_process.poll() is None:
if java_process and java_process.poll() is None:
print("\n🛑 正在关闭 Java 服务...")
java_process.terminate()
print("已关闭Java服务")
try:
java_process.wait(timeout=5)
except subprocess.TimeoutExpired:
java_process.kill()
print("✅ Java 服务已关闭。")
# 确保程序退出时关闭Java进程
# 注册退出钩子
atexit.register(cleanup)
# if __name__ == "__main__":
# # 使用示例
# input_folder = "project2json/uploads"
# output_folder = "project2json/outputs/json"
# print(f"当前工作目录: {os.getcwd()}")
# ==================== 使用示例 ====================
if __name__ == "__main__":
# 示例调用
input_dir = r"project2json/uploads"
output_dir = r"project2json/outputs/json"
# # 检查输入文件夹是否存在
# if not os.path.exists(input_folder):
# print(f"错误: 输入文件夹 '{input_folder}' 不存在")
# # 尝试使用相对于脚本的路径
# script_dir = os.path.dirname(os.path.abspath(__file__))
# alternative_input = os.path.join(script_dir, "uploads")
# print(f"尝试使用替代路径: {alternative_input}")
# if os.path.exists(alternative_input):
# input_folder = alternative_input
# print(f"使用替代输入路径: {input_folder}")
success = convert_project_to_json(input_dir, output_dir)
# # 同样调整输出文件夹
# output_folder = os.path.join(script_dir, "outputs")
# print(f"使用替代输出路径: {output_folder}")
# else:
# print(f"错误: 替代输入路径 '{alternative_input}' 也不存在")
# sys.exit(1)
if success:
print("\n🎉 ✅ 全部流程执行成功!")
else:
print("\n❌ 流程执行失败,请检查日志。")
# # 确保输出文件夹存在
# os.makedirs(output_folder, exist_ok=True)
# try:
# print(f"输入文件夹: {input_folder}")
# print(f"输出文件夹: {output_folder}")
# # 列出输入文件夹中的文件
# print("输入文件夹内容:")
# for file in os.listdir(input_folder):
# print(f" - {file}")
# # 使用正确的函数处理整个文件夹
# result = convert_project_to_json(input_folder, output_folder)
# # 显示处理结果
# if result:
# print("\n处理结果:")
# for src, dst in result:
# print(f" {os.path.basename(src)} -> {os.path.basename(dst)}")
# print(f"\n成功转换 {len(result)} 个文件")
# else:
# print("\n没有文件被成功转换")
# except Exception as e:
# print(f"处理过程中发生错误: {str(e)}")
# import traceback
# traceback.print_exc()
input("\n按回车键退出...")