plan majles

This commit is contained in:
hsafaei
2026-05-09 16:04:08 +03:30
parent cb90e83ba6
commit 488eb98fec
9 changed files with 1570 additions and 824 deletions
+143
View File
@@ -0,0 +1,143 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import zipfile
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.elastic_helper import ElasticHelper
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.data_helper import DataHelper
text_normal = TextNormalizer()
def get_evaluation_data(data):
result = []
if data.is_subject_unity_assessment_correct:
result.append("تایید وجود وحدت موضوعی")
else:
result.append("رد وجود وحدت موضوعی")
if data.is_conflict_detection_correct:
result.append("تایید تشخیص مخالفت")
else:
result.append("رد تشخیص مخالفت")
if data.is_conflict_type_detection_correct:
result.append("تایید تشخیص نوع مخالفت")
else:
result.append("رد تشخیص نوع مخالفت")
if data.is_relation_type_detection_correct:
result.append("تایید تشخیص نوع تعارض")
else:
result.append("رد تشخیص نوع تعارض")
return result
def get_vlid_text(text):
if text == "valid":
return "معتبر"
elif text == "invalid":
return "نامعتبر"
elif text == "undetermined":
return "نامشخص"
def import_conflict_to_elastic( file_path, out_put_index_name):
data_all = DataHelper.load_orjson(file_path)
bulk_data = []
failed_data = []
total_count = 0
for item in data_all :
_id = item["id"]
previous_info = item["previous_info"]
next_info = item["next_info"]
version_key = item["version_key"]
subject_unity = item["subject_unity"]
conflict_detection = item["conflict_detection"]
conflict_type_detection = item["conflict_type_detection"]
conflict_relation_identification = item["conflict_relation_identification"]
conflict_evaluation = item["conflict_evaluation"]
conflict_final = item["conflict_final"]
es_data = {
"id": _id,
"version_key": version_key,
"previous_info": previous_info,
"next_info": next_info,
"subject_unity": subject_unity,
"conflict_detection": conflict_detection,
"conflict_type_detection":conflict_type_detection,
"conflict_relation_identification":conflict_relation_identification,
"conflict_evaluation": conflict_evaluation,
"conflict_final": conflict_final,
}
bulk_data.append({"_id": _id, "_source": es_data})
if len(bulk_data) > 200:
total_count += len(bulk_data)
print("=" * 10, "to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, out_put_index_name)
bulk_data = []
# break
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, "to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, out_put_index_name)
bulk_data = []
## -----------------------------------------------------------------------
load_dotenv(dotenv_path="config.env")
# host = os.getenv("HOST_160")
# password = os.getenv("HOST_160_PASS")
host = os.getenv("HOST_112")
password = os.getenv("HOST_112_PASS")
# host = os.getenv("HOST_H102")
# password = os.getenv("HOST_H102_PASS")
# print( "---------------->>>>>>>>>>>>>>>", host )
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
print(".... majles_codes_update_steps ......", host)
path_base_map = "G:/Project2/tavasi_160/src/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# import_conflict_to_elastic(
# file_path=r"G:\Project2\102_gpu\v3\output_130k_all_qavanin_persian_translate_full.json",
# out_put_index_name="mj_qa_conflict")
# elastic.backupIndexToZipfile("G:/Project2/111/server160", "mj_qa_conflict", "mj_qa_conflict")
# elastic.createIndex( 'mj_qa_conflict', 'majles', 'mj_qa_conflict', path_base_map+ 'majles/'+'mj_qa_conflict.json' )
# elastic.restorFileToElastic2('G:/Project2/111/server160/mj_qa_conflict.zip', 'mj_qa_conflict', 'majles', False)
## -----------------------------------------------------------------------
# .\.env\Scripts\activate
# python -m app.majles.majles_conflict_works.py
+369
View File
@@ -0,0 +1,369 @@
import os
import re
import uuid
import traceback
import json
import time
import pandas as pd
from dotenv import load_dotenv
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
# from app.common.general_functions import *
from app.common.qanon_functions import *
from app.common.elastic_helper import ElasticHelper
from app.common.config_base import *
from app.common.data_helper import DataHelper
def recersive_sections(
section,
list_bulk,
parent_id,
parent_path,
tcode_label,
child_order,
version_key = "D49_oss120",
):
"""
Recursive helper to process one section (and its subsections).
"""
title = section.get("title", "").strip()
section_list = section.get("section_list", [])
description = section.get("definition", "").strip()
tags = section.get("keywords", [])
ai_section_ids = []
for item in section_list :
if isinstance(item, str) :
ai_section_ids.append(item)
if not title:
return
# Generate node ID
node_id = uuid.uuid4().hex[:8]
full_path = parent_path + title + "/"
# Append current section
list_bulk.append({
"_id": node_id,
"_source":{
"id": node_id,
"title": title,
"version_key": version_key,
"full_path": full_path,
"description": description,
"tags": tags,
"parent_id": parent_id,
"child_order": child_order,
"ai_section_ids": ai_section_ids,
"tcode": tcode_label,
"time_create": int(round(time.time() * 1000))
}
})
# Process subsections (children)
subsections = section.get("subsections", [])
if subsections :
for idx, subsec in enumerate(subsections, start=1):
recersive_sections(
section=subsec,
list_bulk=list_bulk,
parent_id=node_id, # ✅ important: parent is current node
parent_path=full_path, # ✅ path extended
child_order=idx, # ✅ order among child_order
tcode_label=tcode_label,
version_key=version_key
)
def import_paln_json_to_elastic(all_codes, elastic, file_path, index_name, version_key= "D49_oss120"):
try:
# Read JSON file
with open(file_path, 'r', encoding="utf8") as f:
data = json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSON file: {str(e)}")
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {file_path}")
print("-"*10, " ... import_paln_json_to_elastic ....", file_path)
total = len(list(data))
list_bulk = []
batch_size = 20
processed_count = 0
total_update = 0
batch_size_number = 1
file_name = os.path.basename(file_path)
_name = os.path.splitext(file_name)[0]
code_name = _name
tcode_label = data.get("law_title")
item_found = [item for item in all_codes if item.get("title") == tcode_label]
if not item_found :
item_found = [item for item in all_codes if item.get("title") == code_name]
if item_found :
tcode_label = code_name
else :
print("################### error tcode_label , code_name ....", tcode_label, code_name, file_path)
return
# Step 1: Add root node (the law itself)
root_id = uuid.uuid4().hex[:8]
root_path = tcode_label + "/"
# list_bulk.append({
# "_id": root_id,
# "_source": {
# "id": root_id,
# "title": tcode_label,
# "version_key": version_key,
# "full_path": root_path,
# "parent_id": 0, # or 0 if you prefer integer root parent
# "child_order": 0,
# "tcode": tcode_label,
# "time_create": int(round(time.time() * 1000))
# }
# })
# Step 2: Recursively process top-level sections
for idx, section in enumerate(data.get("sections", []), start=1):
# print("..start..", idx, section["title"])
recersive_sections(
section=section,
list_bulk=list_bulk,
parent_id=0,
parent_path=root_path,
child_order=idx,
tcode_label=tcode_label,
version_key= version_key
)
if len(list_bulk) >= batch_size :
elastic.importBulkList(list_bulk, index_name)
total_update += len(list_bulk)
list_bulk = []
# print("updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path)
batch_size_number += 1
if list_bulk:
elastic.importBulkList(list_bulk, index_name)
total_update += len(list_bulk)
# print(" .... finish updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path)
batch_size_number += 1
########################## save manual for test
# file_path = r'D:\\init_mahdi\project\dataParsers\data\plan_test\test1.json'
# with open(file_path, 'w', encoding='utf-8') as f:
# json.dump(list_bulk, f, ensure_ascii=False, indent=4)
# print(':D')
def list_json_files(directory):
import os
json_files = []
# مرور در دایرکتوری
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.json'):
# افزودن مسیر کامل فایل به لیست
json_files.append(os.path.join(root, file))
return json_files
def import_v1(elastic, all_codes, version_key= "D49_oss120"):
index_name='mj_plan'
# file_path=r'data/plans/gpt120b_49_1/data_1/آمار، برنامه و بودجه.json'
file_path=r'data/plans/gpt120b_49_1/data_1/'
for file in list_json_files(file_path):
import_paln_json_to_elastic(
all_codes=all_codes,
elastic=elastic,
file_path=file,
index_name=index_name,
version_key= version_key
)
file_path=r'data/plans/gpt120b_49_1/data_2/'
for file in list_json_files(file_path):
import_paln_json_to_elastic(
all_codes=all_codes,
elastic=elastic,
file_path=file,
index_name=index_name,
version_key= version_key
)
# all_codes = []
# with open("./data/codes49.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1
def import_v2_full_tree(elastic, all_codes, file_path, index_name="mj_plan", list_codes_jump = [], version_key= "D49_oss120_gemma"):
data_all = DataHelper.load_orjson(file_path)
list_bulk = []
total_update = 0
batch_size_number = 0
for key in data_all :
node = data_all[key]
code_name = key.replace("قانون ", "").strip()
item_found = [item for item in all_codes if item.get("title") == code_name]
if not item_found :
print("* " * 10, " error in code_name ", key, code_name)
continue
#-- قبلا درخت همراه شناسه ماده های مرتبط افزوده شده است
if code_name in list_codes_jump :
continue
# print("-"* 10, key)
root_path = code_name + "/"
idx = 0
for item in node :
idx += 1
recersive_sections(
section=item,
list_bulk=list_bulk,
parent_id=0,
parent_path=root_path,
child_order= idx,
tcode_label=code_name,
version_key= version_key,
)
print("-" * 10, code_name, len(list_bulk))
if len(list_bulk) >= 0 :
elastic.importBulkList(list_bulk, index_name)
total_update += len(list_bulk)
list_bulk = []
print("updated batch : ", batch_size_number, f" {total_update} --->", code_name)
batch_size_number += 1
def import_v2_section_list(elastic, all_codes, folder_path, index_name="mj_plan",version_key= "D49_oss120_gemma_matched"):
list_codes_imported = []
files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
for file in files :
file_name = os.path.basename(file)
_name = os.path.splitext(file_name)[0]
_name = _name.replace("_finall_tree", "")
code_name = _name
print('=========================== start code_name ===> ', code_name[::-1])
w1 = text_normalizer.split_words(code_name)[0]
file_path = os.path.join(folder_path, file)
data_tree = {}
root_node = {}
try:
data_tree = DataHelper.load_orjson(file_path)
if data_tree["title"] :
code_name = data_tree["title"]
if data_tree["subsections"] :
root_node = data_tree["subsections"]
except Exception as e:
print(output)
continue
item_found = [item for item in all_codes if item.get("title") == code_name]
if not item_found :
print("* " * 10, " error in code_name ", key, code_name)
continue
list_bulk = []
total_update = 0
batch_size_number = 0
root_path = code_name + "/"
idx = 0
for item in root_node :
idx += 1
recersive_sections(
section=item,
list_bulk=list_bulk,
parent_id=0,
parent_path=root_path,
child_order= idx,
tcode_label=code_name,
version_key= version_key,
)
print("-" * 10, code_name, len(list_bulk))
if len(list_bulk) >= 0 :
elastic.importBulkList(list_bulk, index_name)
total_update += len(list_bulk)
list_bulk = []
print("updated batch : ", batch_size_number, f" {total_update} --->", code_name)
batch_size_number += 1
list_codes_imported.append(code_name)
return list_codes_imported
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
print('.... codes_import_from_excel ......', host)
path_base_map = "G:/Project2/gateway_php/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
all_codes = []
with open("./data/codes49.json", "r", encoding="utf8") as f:
codes_1 = json.load(f)
all_codes = codes_1
## ---------------------------------------------------------
# .\.env\Scripts\activate
# python -m app.majles.majles_plans_import
# import_v1(elastic, all_codes, "D49_oss120")
# list_codes_imported=[]
# file_path = r"G:\Project2\102_gpu\v3\plan_dict_def_keyword.json"
# import_v2_full_tree(elastic, all_codes, file_path, "mj_plan", list_codes_imported, "D49_oss120_gemma")
folder_path = r"G:\Project2\102_gpu\match_plan\v2"
list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_gemma_matched")
-570
View File
@@ -1,570 +0,0 @@
import pandas as pd
import orjson, os, traceback
from pathlib import Path
MN_P2E = {
"۰": "0",
"۱": "1",
"۲": "2",
"۳": "3",
"۴": "4",
"۵": "5",
"۶": "6",
"۷": "7",
"۸": "8",
"۹": "9",
}
MN_E2P = {v: k for k, v in MN_P2E.items()}
def change_to_en(in_text):
if isinstance(in_text, str):
result = ""
for char in in_text:
if char in MN_P2E:
result += MN_P2E[char]
else:
result += char
return result
else:
return in_text
def load_orjson(path: str | Path):
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
def save_orjson(path, data):
with open(path, "wb") as f:
f.write(
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
)
def extract_excel_fields(file_path: str, fields: list = [], sheet_name: str = None):
"""
فایل اکسل را باز کرده و فقط فیلدهای خواسته‌شده را به‌صورت لیست از دیکشنری‌ها برمی‌گرداند.
:param file_path: مسیر فایل اکسل (.xlsx یا .xls)
:param fields: لیست نام ستون‌هایی که باید خوانده شوند
:return: لیستی از دیکشنری‌ها شامل داده‌های ستون‌های انتخاب‌شده
"""
try:
# خواندن فایل
df = pd.read_excel(file_path, sheet_name=sheet_name)
df.columns = df.columns.map(str)
if len(fields) > 0:
missing = [f for f in fields if f not in df.columns]
if missing:
print(f"⚠️ This columns mot found in file {missing}")
# for i in df.columns:
# print(f'-field ->{i}<-')
df = df[[f for f in fields if f in df.columns]]
# تبدیل به لیست از دیکشنری‌ها
data = df.to_dict(orient="records")
return data
except Exception as e:
print(f"❌ خطا در خواندن فایل اکسل: {e}")
return []
def save_excel(file_path: str, data: list):
"""ذخیره‌ی داده‌ها در فایل اکسل جدید"""
try:
df = pd.DataFrame(data)
df.to_excel(file_path, index=False)
print(f"✅ فایل با موفقیت ذخیره شد: {file_path}")
except Exception as e:
print(f"❌ خطا در ذخیره فایل اکسل: {e}")
def normalize_dict_number_value(in_list: dict):
f_list = []
for item_dict in in_list:
f_dict = {}
for k, v in item_dict.items():
f_dict[k] = change_to_en(v)
f_list.append(f_dict)
return f_list
def split_object_m2m(in_text: str):
if not isinstance(in_text, str):
print(type(in_text))
valid_char = set("0123456798/.")
set_text = set(in_text)
if set_text == set("."):
return []
f_list = []
_id = []
for i in in_text:
if i in valid_char:
_id.append(i)
else:
if len(_id) > 0:
f_list.append("".join(_id))
_id = []
if len(_id) > 0:
f_list.append("".join(_id))
_id = []
return f_list
###########################################استخراج داده های اکسل ها در جیسون#############################
# all_json = []
# for u in [9,10,11,12]:
# json_data = extract_excel_fields(
# file_path=r'D:\init_mahdi\hsafaei_task\task_excel_\input\1.daftar sabt parvandeha1_clean.xlsx',
# fields=[], # "شماره ثبت", "شماره پرونده"
# sheet_name=str(u)
# )
# for item in json_data:
# sabt = split_object_m2m(str(item["شماره ثبت"]))
# parvande = split_object_m2m(str(item["شماره پرونده"]))
# item["شماره ثبت"] = sabt
# item["شماره پرونده"] = parvande
# all_json += json_data
# print(f'all_json {len(all_json)}')
# save_orjson(
# data=all_json,
# path=r'D:\init_mahdi\hsafaei_task\task_excel_\procces\map\all_map_full_data.json',
# )
########################################################################
####################### روش دوم و نهایی ذخیره در یک فایل ##################################
map_all_tarh = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\map\map_tarh_9101112.json"
)
all_map_data = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\map\all_map_full_data.json"
)
all_data = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\all_data\qavanin_output4_4field.json"
)
tarh_9 = load_orjson(r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_9.json")
tarh_10 = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_10.json"
)
tarh_11 = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_11.json"
)
tarh_12 = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_12.json"
)
dict_all_map_data = {
i["شماره پرونده"][0].replace(".", "/"): {
"شماره ثبت وسطی": " و ".join(i["شماره ثبت"]),
"شماره شناسه وسطی": i["شماره شناسه"],
"شماره پرونده وسطی": " و ".join(i["شماره پرونده"]),
}
for i in all_map_data
}
print(f"map_all_tarh {len(map_all_tarh)}")
dict_map_tarh = {
i["شماره پرونده"][0].replace(".", "/"): i["شماره ثبت"] for i in map_all_tarh
}
print(f"dict_map_tarh {len(dict_map_tarh)}")
parvande_sabt_dict = {}
for n_parvande, n_sabt in dict_map_tarh.items():
if isinstance(n_sabt, list) and len(n_sabt) == 1:
parvande_sabt_dict[n_parvande] = n_sabt[0]
elif isinstance(n_sabt, list) and len(n_sabt) >= 1:
high_priority = -1
priority_data = None
for item2 in n_sabt:
### way1: all list
# sabt_parvande_data[item2] = item
## way2: Just One
if "/" in item2:
seperator = "/"
elif "." in item2:
seperator = "."
else:
print(f"not any seperator {item2}")
priority = int(item2.split(seperator)[0])
if high_priority < priority:
high_priority = priority
priority_data = item2
if priority_data:
parvande_sabt_dict[n_parvande] = priority_data
else:
print(f"not found priority {priority} high_priority {high_priority}")
else:
pass
print(f"parvande_sabt_dict {len(parvande_sabt_dict)}")
dict_sabt_tarh = {}
for i in [[tarh_9, 9], [tarh_10, 10], [tarh_11, 11], [tarh_12, 12]]:
tarh = i[0]
tarh_number = i[1]
for item in tarh:
dict_sabt_tarh[str(tarh_number) + "/" + change_to_en(item["شماره ثبت"])] = item
dict_parvande_sabt_data = {}
for k, v in parvande_sabt_dict.items():
sabt_number = change_to_en(v)
data = dict_sabt_tarh.get(sabt_number, None)
if data:
dict_parvande_sabt_data[k] = data
print(f"dict_parvande_sabt_data {len(dict_parvande_sabt_data)}")
print(f"all_data {len(all_data)}")
f_data = load_orjson(
r"D:\init_mahdi\hsafaei_task\task_excel_\procces\all_data\qavanin_output4_after_islamic_revolution.json"
)
fields = [
"شماره عمومی",
"شماره رديف",
"شماره پرونده",
"دوره قانونگذاری",
"عنوان",
"تاریخ تصویب",
"_id",
]
filtered_data = []
for i in f_data:
filtered_item = {}
for field in fields:
if field in i: #
filtered_item[field] = i[field]
else:
filtered_item[field] = None # Assign None as the default value
print(f"Warning: Field '{field}' not found in item: {i}")
filtered_data.append(filtered_item)
valid = 0
for item in filtered_data:
parvande_number = item["شماره پرونده"] # .replace('.',"/")
_data = dict_parvande_sabt_data.get(parvande_number, None)
_data2 = dict_all_map_data.get(parvande_number, None)
if _data and _data2:
valid += 1
item.update(_data)
item.update(_data2)
print(f"valid {valid}")
save_excel(
data=filtered_data,
file_path=r"D:\init_mahdi\hsafaei_task\task_excel_\output\excel\finall_finall.xlsx",
)
print(":D")
################## روش اول ذخیره در فایل های طرح ها ########
# if __name__ == "__main__":
# """Tarh: 9-10-11-12"""
# json_all_data = []
# number_of_sabt = 0
# number_of_parvande = 0
# for u in [9,10,11,12]:
# json_data = extract_excel_fields(
# file_path=r'D:\init_mahdi\hsafaei_task\task_excel_\input\1.daftar sabt parvandeha1_clean.xlsx',
# fields=["شماره ثبت", "شماره پرونده"],
# sheet_name=str(u)
# )
# _number_of_sabt = 0
# _number_of_parvande = 0
# for i in json_data:
# sabt = split_object_m2m(str(i["شماره ثبت"]))
# parvande = split_object_m2m(str(i["شماره پرونده"]))
# _number_of_sabt += len(sabt)
# _number_of_parvande += len(parvande)
# json_all_data += [
# {
# "شماره ثبت": sabt,
# "شماره پرونده": parvande
# }
# ]
# number_of_sabt+=_number_of_sabt
# number_of_parvande+=_number_of_parvande
# print(
# f"_number_of_sabt {_number_of_sabt}",
# f"_number_of_parvande {_number_of_parvande}",
# )
# print(f'=== {u}/{len(json_all_data)}===')
# print(
# f"number_of_sabt {number_of_sabt}",
# f"number_of_parvande {number_of_parvande}",
# )
# save_orjson(
# data=json_all_data,
# path=f'D:\\init_mahdi\\hsafaei_task\\task_excel_\\procces\\map_tarh_9101112.json',
# )
# json_data = load_orjson(r'D:\init_mahdi\hsafaei_task\task_excel_\output\map_m2m_tarh10.json')
# print(f'json_data {len(json_data)}')
# f_list = []
# for in_dict in json_data:
# _dict = {}
# for k, v in in_dict.items():
# _dict[k] = split_object_m2m(v)
# f_list.append(_dict)
# print(f'json_data {len(f_list)}')
# split_object_m2m
# save_orjson(
# path=r'D:\init_mahdi\hsafaei_task\task_excel_\output\map_m2m_tarh10_1.json',
# data=f_list
# )
##########################################################
# json_data = extract_excel_fields(
# file_path=r'D:\init_mahdi\hsafaei_task\task_excel_\input\طرح های دوره نهم.xlsx',
# fields=[],
# sheet_name="Export"
# )
# save_orjson(
# data=json_data,
# path=f'D:\\init_mahdi\\hsafaei_task\\task_excel_\\procces\\tarh\\tarh_9.json',
# )
# print(
# f'tarh_9 {len(json_data)}'
# )
##########################################################
# Validation شماره ثبت و شماره پرونده
# مرجع فایل دوره دهم است
# ##########################################################
# map_all_tarh = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\map\map_tarh_9101112.json"
# )
# all_data = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\all_data\qavanin_output4_4field.json"
# )
# tarh_9 = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_9.json"
# )
# tarh_10 = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_10.json"
# )
# tarh_11 = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_11.json"
# )
# tarh_12 = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\tarh\tarh_12.json"
# )
# dict_map_tarh = {i["شماره پرونده"][0]: i["شماره ثبت"] for i in map_all_tarh}
# print(f"all_data {len(all_data)}")
# sabt_parvande_data = {}
# for item in all_data:
# data_qq_id = str(item["_id"])
# data_shomare_omomi = str(item["شماره عمومی"])
# data_radif = str(item["شماره رديف"])
# data_parvande = str(item["شماره پرونده"])
# map_data = dict_map_tarh.get(data_parvande, None) # list az shomare sabt ha ast
# if map_data:
# if len(map_data) == 1:
# sabt_parvande_data[map_data[0]] = item
# else:
# high_priority = -1
# priority_data = None
# for item2 in map_data:
# ### way1: all list
# # sabt_parvande_data[item2] = item
# ## way2: Just One
# if "/" in item2:
# seperator = "/"
# elif "." in item2:
# seperator = "."
# else:
# print(f"not any seperator {item2}")
# priority = int(item2.split(seperator)[0])
# if high_priority < priority:
# high_priority = priority
# priority_data = item2
# if priority_data:
# sabt_parvande_data[priority_data] = item
# else:
# print(f"not found priority_data {item2}")
# print(f"تعداد شماره پرونده های موجود در clean mapping ها {len(sabt_parvande_data)}")
# # for i, (k, v) in enumerate(sabt_parvande_data.items(), start=1):
# # print(k, v)
# # break
# finally_number = 0
# error_number = 0
# all_parvande_data = {}
# for _tarh in [[tarh_9, 9], [tarh_10, 10], [tarh_11, 11], [tarh_12, 12]]:
# tarh = _tarh[0]
# tarh_number = _tarh[1]
# for item in tarh:
# temp_item = {}
# try:
# try:
# sabt_number = f"{tarh_number}/" + change_to_en(item["شماره ثبت"])
# sabt_number = sabt_number.strip()
# item_data = sabt_parvande_data[sabt_number]
# temp_item["شماره پرونده"] = item_data["شماره پرونده"]
# temp_item["شماره رديف"] = item_data["شماره رديف"]
# temp_item["شماره عمومی"] = item_data["شماره عمومی"]
# temp_item["_id"] = item_data["_id"]
# finally_number += 1
# all_parvande_data[item_data["شماره پرونده"]] = temp_item
# except:
# sabt_number = f"{tarh_number}." + change_to_en(item["شماره ثبت"])
# sabt_number = sabt_number.strip()
# item_data = sabt_parvande_data[sabt_number]
# temp_item["شماره پرونده"] = item_data["شماره پرونده"]
# temp_item["شماره رديف"] = item_data["شماره رديف"]
# temp_item["شماره عمومی"] = item_data["شماره عمومی"]
# temp_item["_id"] = item_data["_id"]
# finally_number += 1
# all_parvande_data[item_data["شماره پرونده"]] = temp_item
# except Exception as e:
# error_number += 1
# print(f"error_number {error_number}")
# # print(f"TRACEBACK {traceback.print_exc()}")
# print(f"all_parvande_data {len(all_parvande_data)}")
# f_data = load_orjson(
# r"D:\init_mahdi\hsafaei_task\task_excel_\procces\all_data\qavanin_output4_after_islamic_revolution.json"
# )
# fields = [
# "شماره عمومی",
# "شماره رديف",
# "شماره پرونده",
# "دوره قانونگذاری",
# "عنوان",
# "تاریخ تصویب",
# "_id",
# ]
# filtered_data = []
# for i in f_data:
# filtered_item = {}
# for field in fields:
# if field in i: #
# filtered_item[field] = i[field]
# else:
# filtered_item[field] = None # Assign None as the default value
# print(f"Warning: Field '{field}' not found in item: {i}")
# filtered_data.append(filtered_item)
# for i in filtered_data:
# if
# print(f"filtered_data {len(filtered_data)} {filtered_data[0]}")
# # soreted_tarh = []
# # for i, item in enumerate(tarh_12, start=1):
# # if change_to_en(item["ردیف"]).strip() == str(i):
# # soreted_tarh.append(item)
# # print(
# # f"tarh_{tarh_number} {len(tarh_12)}",
# # f"f_tarh_{tarh_number} {len(soreted_tarh)}",
# # f"finally_number {finally_number}",
# # f"error_number {error_number}",
# # sep="\n",
# # )
# # save_orjson(
# # data=soreted_tarh,
# # path=f"D:\\init_mahdi\\hsafaei_task\\task_excel_\\output\\json\\{tarh_number}.json",
# # )
# # save_excel(
# # data=soreted_tarh,
# # file_path=f"D:\\init_mahdi\\hsafaei_task\\task_excel_\\output\\excel\\{tarh_number}.xlsx",
# # )
# print(":D")
"""
Report:
-all_data
after islamic revolution -> 4499
-map-all:
=== 9/403===
_number_of_sabt 448 _number_of_parvande 403
=== 10/745=== یک فیلد خالی
_number_of_sabt 419 _number_of_parvande 341
=== 11/1027===
_number_of_sabt 378 _number_of_parvande 282
=== 12/1109===
_number_of_sabt 109 _number_of_parvande 82
=== total 4 tarh -> number_of_sabt 1354 number_of_parvande 1108
-tarh-all:
tarh_9 602
tarh_10 801
tarh_11 1122
tarh_12 381
totall tarh -> 2906
تعداد شماره پرونده های موجود در clean mapping ها بر اساس بالاترین دوره 529
- finall
- tarh 9:
f_tarh_9 602
finally_number 173
error_number 429
- tarh 10:
f_tarh_10 801
finally_number 179
error_number 622
- tarh 11:
f_tarh_11 1122
finally_number 135
error_number 987
- tarh 12:
f_tarh_12 381
finally_number 6
error_number 375
تعداد پیدا شده ها و متصل شده ها در نهایت به صورت کلی: 493
"""
"""
تعداد تمام داده ها:
4499
تعداد map ها در داده های 1.daftar sabt parvandeha1_clean:
1108
تعداد داده های صحیح 1.daftar sabt parvandeha1_clean:
1098
تعداد داده هایی که هم در 1.daftar sabt parvandeha1_clean موجود بودند و هم در qavanin_output4 :
931
"""