import pandas as pd import requests import json import os 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") column_names = df.columns.tolist() 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["LEVEL"] = int(row["سطح"]) row["CODE"] = row.get("کد", "") return data, column_names # 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_old(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 insert_real(rows, projectid, IDS_DICT, column_names,otherid): remains = [] dic_level_parent = {1:0} child_count = {} prev_level = 0 prev_id = 0 new_row_list=[] column_count = len(column_names) for row in rows: row_id = row["ID"] caption = row["CAPTION"] level = row["LEVEL"] parent = 0 if level == 1 : parent = 0 elif level == prev_level+1 : parent = prev_id dic_level_parent[level]=prev_id elif level in dic_level_parent: parent = dic_level_parent[level] else : print("error", level, row_id) child_order = child_count.get(parent, 0) + 1 child_count[parent] = child_order row[column_count+1] = parent row[column_count+2] = child_order new_row_list.append(row) # آماده‌سازی درخواست body = { "title": caption, "projectid": projectid, "otherid": otherid, "meta": row.get("CODE", ""), "child_order": child_order, "listtype": 0, "parent": parent, } prev_level = level try: response = requests.post( BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=body, 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}") prev_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, **body } return new_row_list def process_excel_data(file_path , sheet_name): row_list, column_names = read_excel_data(file_path , sheet_name) row_list = sorted(row_list, key=lambda x: x["ID"]) print(f"❗️ Parent not found for F_PARENTID={row_list}") IDS_DICT = {} childs = {} projectid = insert_project(sheet_name) otherid = projectid-100 if not projectid: return print("🚀 شروع درج داده‌ها") rows_list_new = insert_real(row_list, projectid, IDS_DICT, column_names , otherid) column_count=len(column_names) column_names.append(column_count+1) column_names.append(column_count+2) columns=column_names new_df = pd.DataFrame(rows_list_new, columns=columns) result_path = os.path.dirname(file_path) file_name = sheet_name file_excel2 = result_path +'/پلن-'+ file_name + '.xlsx' # print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2) # new_df.to_excel(file_excel2, index=False, engine='openpyxl') # 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)