Files
init_dataParser/r4_import_plan_excel.py
T

134 lines
4.1 KiB
Python

import pandas as pd
import requests
import json
from text_normalizer import TextNormalizer
from config_base import *
from general_functions import *
ADD_ITEM_ROUTE = "subject/add"
# TITLE = ""
def read_excel_data(file_path ,sheet_name):
df = pd.read_excel(file_path , sheet_name=sheet_name)
df.fillna("", inplace=True)
data = df.to_dict(orient="records")
text_normal = TextNormalizer()
for row in data:
row["CAPTION"] = text_normal.normalize_qanon(row["عنوان"])
row["ID"] = int(row["ردیف"])
row["F_PARENTID"] = int(row["سطح"]) - 1 if row["سطح"] > 1 else 0
row["CODE"] = row.get("کد", "")
return data
# def insert_project():
# projectid = 7 # فرض کنید projectid ثابت است
# return projectid
def insert_project(sheet_name):
json_file = 'کدهای 50 گانه.json'
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
for row in data:
if row.get("title") == sheet_name:
base_id = row.get("otherid", 0)
return base_id + 100 # افزایش ۱۰۰ واحدی
print(f"❌ Sheet name '{sheet_name}' not found in JSON data.")
return None
def insert_real(rows, projectid, IDS_DICT, childs,otherid):
remains = []
for row in rows:
try:
f_parentid = row["F_PARENTID"]
row_id = row["ID"]
caption = row["CAPTION"]
except KeyError:
print("Missing data in row:", row)
continue
# تعیین والد
if f_parentid == 0:
parent = 0
elif str(f_parentid) in IDS_DICT:
parent = IDS_DICT[str(f_parentid)]["id"]
else:
print(f"❗️ Parent not found for F_PARENTID={f_parentid}")
remains.append(row)
continue
# محاسبه شماره فرزند
number = childs.get(parent, 0) + 1
childs[parent] = number
# آماده‌سازی درخواست
ADD_ITEM_QUERY = {
"title": caption,
"projectid": projectid,
"otherid": otherid,
"meta": row.get("CODE", ""),
"childorder": number,
"listtype": 0,
"parent": parent,
}
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE,
data=ADD_ITEM_QUERY,
headers=HEADERS
)
response.raise_for_status()
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ {row_id}: {caption} -> ID={new_id}")
except Exception as e:
print(f"❌ Failed to insert {caption}: {e}")
remains.append(row)
continue
IDS_DICT[str(row_id)] = {
"id": new_id,
**ADD_ITEM_QUERY
}
return remains
def process_excel_data(file_path , sheet_name):
data = read_excel_data(file_path , sheet_name)
data = sorted(data, key=lambda x: x["ID"])
print(f"❗️ Parent not found for F_PARENTID={data}")
IDS_DICT = {}
childs = {}
projectid = insert_project(sheet_name)
otherid = insert_project(sheet_name)-100
if not projectid:
return
print("🚀 شروع درج داده‌ها")
remains = insert_real(data, projectid, IDS_DICT, childs , otherid)
count = 1
while remains and count < 3:
print(f"\n🔁 تلاش مجدد {count}: باقی‌مانده {len(remains)} آیتم")
remains = insert_real(remains, projectid, IDS_DICT, childs ,otherid)
count += 1
json_file_path = f'{sheet_name}.json'
with open(json_file_path, "w", encoding="utf-8") as file:
json.dump(IDS_DICT, file, ensure_ascii=False, indent=4)
print(f"\n✅ تمام داده‌ها ثبت شدند و در {sheet_name} ذخیره شدند.")
if __name__ == "__main__":
file_path = "data/Plan.xlsx"
# sheet_name = 'آموزش و پرورش'
sheet_name = 'مناطق آزاد و ویژه اقتصادی'
# sheet_name = 'فرهنگ و هنر'
process_excel_data(file_path , sheet_name)