102 lines
3.1 KiB
Python
Executable File
102 lines
3.1 KiB
Python
Executable File
import os
|
|
import json
|
|
|
|
# def deep_json_load(s):
|
|
# """Decode multi-level stringified JSON safely."""
|
|
# while isinstance(s, str):
|
|
# try:
|
|
# s = json.loads(s)
|
|
# except Exception:
|
|
# break
|
|
# return s
|
|
|
|
|
|
# def fix_json_directory(src_dir, dst_dir):
|
|
# """
|
|
# Decode all stringified JSON files from src_dir
|
|
# and save corrected JSONs into dst_dir.
|
|
# """
|
|
# os.makedirs(dst_dir, exist_ok=True)
|
|
# files = [f for f in os.listdir(src_dir) if f.lower().endswith(".json")]
|
|
# print(len(files))
|
|
# # for fname in files:
|
|
|
|
# # src_path = os.path.join(src_dir, fname)
|
|
# # dst_path = os.path.join(dst_dir, fname)
|
|
|
|
# # try:
|
|
# # # خواندن فایل منبع
|
|
# # with open(src_path, "r", encoding="utf-8") as f:
|
|
# # raw = f.read().strip()
|
|
|
|
# # # تبدیل به ساختار واقعی
|
|
# # data = deep_json_load(raw)
|
|
|
|
# # # ذخیره در مسیر مقصد با فرمت زیبا
|
|
# # with open(dst_path, "w", encoding="utf-8") as out:
|
|
# # json.dump(data, out, ensure_ascii=False, indent=2)
|
|
|
|
# # print(f"✅ Fixed: {fname}")
|
|
|
|
# # except Exception as e:
|
|
# # print(f"⚠️ Error in {fname}: {e}")
|
|
|
|
# # print(f"\n🎯 Done. Fixed files saved to: {dst_dir}")
|
|
|
|
# src_dir='/home1/ava3/plan_proccess/finall_arch_data_json'
|
|
# dst_dir='/home1/ava3/plan_proccess/finall_arch_data_multi_1'
|
|
|
|
# fix_json_directory(src_dir, dst_dir)
|
|
|
|
# ------------------------------- moddularity
|
|
import os
|
|
# import pandas as pd
|
|
import orjson
|
|
import json
|
|
import re
|
|
import unicodedata
|
|
import tiktoken
|
|
import orjson
|
|
from typing import List, Optional
|
|
from pydantic import BaseModel, validator
|
|
from pathlib import Path
|
|
|
|
import os
|
|
import json
|
|
|
|
def make_json_from_dir(src_dir, out_file="./merged.json"):
|
|
"""
|
|
تمام فایلهای متنی داخل src_dir را میخواند،
|
|
محتوا را در یک JSON با کلید نام فایل ذخیره میکند،
|
|
و escape لازم برای JSON را اعمال میکند.
|
|
"""
|
|
result = {}
|
|
folder_name = os.path.basename(os.path.abspath(src_dir))
|
|
|
|
for fname in os.listdir(src_dir):
|
|
if not fname.lower().endswith(".txt"):
|
|
continue
|
|
|
|
fpath = os.path.join(src_dir, fname)
|
|
try:
|
|
with open(fpath, "r", encoding="utf-8") as f:
|
|
text = f.read()
|
|
|
|
# حذف تب و خط جدید واقعی و تبدیل به escape sequence
|
|
escaped_text = text.replace("\r", "").replace("\n", "\\n").replace("\t", "\\t")
|
|
|
|
# افزودن به دیکشنری نهایی
|
|
result[fname] = escaped_text
|
|
|
|
except Exception as e:
|
|
print(f"⚠️ Error reading {fname}: {e}")
|
|
|
|
# خروجی JSON نهایی با نام فولدر
|
|
final_json = {folder_name: result}
|
|
|
|
with open(out_file, "w", encoding="utf-8") as f:
|
|
json.dump(final_json, f, ensure_ascii=False, indent=2)
|
|
|
|
print(f"✅ Done! Saved to {out_file}")
|
|
|
|
make_json_from_dir('/home1/ava3/plan_proccess/txt') |