Upload files to "/"

This commit is contained in:
2024-12-20 09:59:57 +08:00
parent fcc3b22c47
commit 0ddbc39b71
3 changed files with 217 additions and 0 deletions

59
json-to-docx.py Normal file
View File

@@ -0,0 +1,59 @@
import json
import argparse
from docx import Document
import os
import glob
def json_to_docx(input_paths, output_path, show_name):
document = Document()
for input_path in input_paths:
with open(input_path, 'r', encoding='utf-8') as f:
data = json.load(f)
for entry in data:
if show_name and 'name' in entry:
paragraph = document.add_paragraph()
paragraph.add_run(entry['name']).bold = True
paragraph.add_run('\n' + entry['message'])
else:
paragraph = document.add_paragraph(entry['message'])
document.save(output_path)
def get_json_files_from_directory(directory):
# 获取指定目录下所有的 JSON 文件
return glob.glob(os.path.join(directory, '*.json'))
def main():
parser = argparse.ArgumentParser(description='Convert JSON messages to DOCX format.')
parser.add_argument('input', nargs='+', help='Input JSON file paths or directory.')
parser.add_argument('-o', '--output', help='Output DOCX file path.', default=None)
parser.add_argument('-n', '--noname', action='store_true', help='Do not include name field in output.')
args = parser.parse_args()
input_files = []
for input_path in args.input:
if os.path.isdir(input_path):
# 如果是目录,则获取该目录下的所有 JSON 文件
input_files.extend(get_json_files_from_directory(input_path))
elif os.path.isfile(input_path) and input_path.endswith('.json'):
# 如果是单个文件,直接添加到列表
input_files.append(input_path)
if not input_files:
print("No JSON files found in the specified paths.")
return
if args.output is None:
# 如果没有指定输出路径,使用第一个输入路径并将扩展名改为 .docx
output_path = os.path.splitext(input_files[0])[0] + '.docx'
else:
output_path = args.output
json_to_docx(input_files, output_path, not args.noname)
print(f'DOCX file saved to: {output_path}')
if __name__ == '__main__':
main()

67
merge-messages.py Normal file
View File

@@ -0,0 +1,67 @@
import os
import json
import argparse
import sys
from typing import Dict, List
def merge_json_files(src_folder: str, dst_folder: str, output_folder: str):
# 创建输出文件夹(如果不存在)
os.makedirs(output_folder, exist_ok=True)
# 遍历源文件夹中的所有文件
for filename in os.listdir(src_folder):
if filename.endswith('.json'):
src_file_path = os.path.join(src_folder, filename)
dst_file_path = os.path.join(dst_folder, filename)
# 检查目标文件夹中是否有对应的文件
if os.path.exists(dst_file_path):
with open(src_file_path, 'r', encoding='utf-8') as src_file:
src_data = json.load(src_file)
with open(dst_file_path, 'r', encoding='utf-8') as dst_file:
dst_data = json.load(dst_file)
# 检查两个 JSON 数组的长度是否一致
if len(src_data) != len(dst_data):
print(f"Error: The JSON files {filename} have different lengths.")
sys.exit(1)
# 合并 JSON 数据
merged_data = []
for index in range(len(src_data)):
src_item = src_data[index]
dst_item = dst_data[index]
message_src = src_item.get('message', '')
message_dst = dst_item.get('message', '')
# 创建合并后的项,只保留存在的 name
merged_item = {}
if 'name' in src_item:
merged_item['src_name'] = src_item['name']
if 'name' in dst_item:
merged_item['dst_name'] = dst_item['name']
# 将 src 和 dst 消息直接添加到合并项中
merged_item['src'] = message_src
merged_item['dst'] = message_dst
merged_data.append(merged_item)
# 输出合并的 JSON 文件
output_file_path = os.path.join(output_folder, filename)
with open(output_file_path, 'w', encoding='utf-8') as output_file:
json.dump(merged_data, output_file, ensure_ascii=False, indent=2)
def main():
parser = argparse.ArgumentParser(description='Merge JSON files from two folders and output to another folder.')
parser.add_argument('src_folder', type=str, help='The source folder containing JSON files.')
parser.add_argument('dst_folder', type=str, help='The destination folder containing JSON files to merge with.')
parser.add_argument('output_folder', type=str, help='The output folder where merged files will be saved.')
args = parser.parse_args()
merge_json_files(args.src_folder, args.dst_folder, args.output_folder)
if __name__ == '__main__':
main()

91
patch_bp.py Normal file
View File

@@ -0,0 +1,91 @@
import argparse
import os
import struct
def parse_arguments():
parser = argparse.ArgumentParser(description='Replace text in a binary file based on a mapping file.')
parser.add_argument('bp_file', type=str, help='The path to the binary file.')
parser.add_argument('txt_file', type=str, help='The path to the text file containing replacements.')
parser.add_argument('out_bp_file', type=str, nargs='?', help='The output binary file path. If not specified, will add "_out" to bp_file.')
return parser.parse_args()
def read_replacements(txt_file):
replacements = {}
with open(txt_file, 'r', encoding='utf-8') as f:
while True:
original_line = f.readline()
if not original_line:
break
original_line = original_line.strip()
if not original_line:
continue
translation_line = f.readline().rstrip('\n')
if translation_line: # Skip if translation is empty
# Extract the hex address and original text
hex_address, original_text = original_line.split(']', 1)
hex_address = hex_address.strip('[')
address = int(hex_address, 16)
translation_line = translation_line.split(']', 1)[1]
if not translation_line:
continue
replacements[address] = (original_text.encode('cp932'), translation_line.encode('utf-8'))
return replacements
def replace_text_in_bp(bp_file, replacements):
with open(bp_file, 'rb') as f:
data = bytearray(f.read())
for address, (original_text, translation_text) in replacements.items():
olen = len(original_text)
tlen = len(translation_text)
data[address:address + olen] = translation_text + b' ' * (olen - tlen)
print(address, olen, tlen, original_text.decode('cp932'), translation_text.decode(), data[address:address + olen])
return data
# def replace_text_in_bp(bp_file, replacements):
# with open(bp_file, 'rb') as f:
# data = f.read()
# offset = 0
# for address, (original_text, translation_text) in replacements.items():
# olen = len(original_text)
# tlen = len(translation_text)
# address += offset
# data = data[:address] + translation_text + data[address+olen:]
# print(address, offset, olen, tlen, original_text.decode('cp932'), translation_text.decode(), data[address:address + tlen])
# offset += tlen - olen
# data = bytearray(data)
# header = struct.unpack('<I', data[0:4])[0]
# size = struct.unpack('<I', data[4:8])[0]
# print(header, size)
# data[4:8] = struct.pack('<I', len(data) - header)
# size = struct.unpack('<I', data[4:8])[0]
# print(len(data) - header, size)
# return data
def main():
args = parse_arguments()
# Determine output file path
if args.out_bp_file:
out_bp_file = args.out_bp_file
else:
out_bp_file = f"{os.path.splitext(args.bp_file)[0]}_out{os.path.splitext(args.bp_file)[1]}"
# Read replacements from the txt file
replacements = read_replacements(args.txt_file)
# Replace text in the binary file
modified_data = replace_text_in_bp(args.bp_file, replacements)
# Write the modified data to the output file
with open(out_bp_file, 'wb') as f:
f.write(modified_data)
print(f'Modified binary file written to: {out_bp_file}')
if __name__ == '__main__':
main()