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
+1 -6
View File
@@ -18,11 +18,6 @@ from app.for_ai.codes_import_from_excel import (
run_codes_extract_directory,
run_codes_to_elastic_directory,
)
from app.parvande_qanon.s2_import_qavanin_excels_to_elastic import (
import_excel_before_to_elastic,
import_excel_after_to_elastic,
import_excel_tasmimat_to_elastic,
)
from app.majles.repair_qa_qanon_for_map_new import *
text_normal = TextNormalizer()
@@ -147,6 +142,6 @@ col_index = {
"state_match" : 7,
}
##--- استخراج موارد خطای کد
run_codes_extract_directory("./data/tcodes/corrected_majles/not_edit4/result","./data/tcodes/corrected_majles/not_edit4/result_json",all_codes,col_index, head_top=False, by_repair_error = True, elastic=elastic)
# run_codes_extract_directory("./data/tcodes/corrected_majles/not_edit4/result","./data/tcodes/corrected_majles/not_edit4/result_json",all_codes,col_index, head_top=False, by_repair_error = True, elastic=elastic)
-214
View File
@@ -1,214 +0,0 @@
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 *
def recersive_sections(
section,
list_bulk,
parent_id,
parent_path,
tcode_label,
child_order,
):
"""
Recursive helper to process one section (and its subsections).
"""
title = section.get("title", "").strip()
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": "D49_oss120",
"full_path": full_path,
"parent_id": parent_id,
"child_order": child_order,
"tcode": tcode_label,
"time_create": int(round(time.time() * 1000))
}
})
# Process subsections (children)
subsections = section.get("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
)
def import_paln_json_to_elastic(all_codes, elastic, file_path, index_name):
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": "D49_oss120",
# "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
)
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
# -------------------------------------------------------------------- Run
if __name__ == "__main__":
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
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
)
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
)
# all_codes = []
# with open("./data/codes49.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1
+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
"""
@@ -325,7 +325,7 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o, duplicate_li
id = ""
try:
data = excel_to_json(path_file, None, 0)
data = excel_to_json(path_file, None, 1)
print('*' * 20 , ' count=', len(data))
cols = [
@@ -663,3 +663,7 @@ def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o, duplicate
traceback.print_exc()
##-------------------------------------------------
##--- استفاده و اجرا در فایل زیر انجام شد
##--- majles_update_2_steps.py
##-------------------------------------------------
+453
View File
@@ -0,0 +1,453 @@
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()}
PATH_BASE = "./data/qavanin_files/"
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
def excel_sabt_vaset_to_json(
file_excel=PATH_BASE + "1.daftar sabt parvandeha1_clean.xlsx",
file_out=PATH_BASE + "result/all_map_full_data.json",
):
all_json = []
for u in [9, 10, 11, 12]:
json_data = extract_excel_fields(
file_path=file_excel,
fields=[], # "شماره ثبت", "شماره پرونده"
sheet_name=str(u),
)
for item in json_data:
sabt = split_object_m2m(str(item["شماره ثبت"]).replace(".", "/"))
parvande = split_object_m2m(str(item["شماره پرونده"]).replace(".", "/"))
item["شماره ثبت"] = sabt
item["شماره پرونده"] = parvande
all_json += json_data
print(f"all_json {len(all_json)}")
save_orjson(
data=all_json,
path=file_out,
)
def excel_sabt_info_to_json():
# ---------------------------------------
json_data = extract_excel_fields(
file_path=PATH_BASE + r"sabt/طرح های دوره نهم.xlsx",
fields=[],
sheet_name="Export",
)
save_orjson(
data=json_data,
path=PATH_BASE + f"sabt/tarh_9.json",
)
print(f"tarh_9 {len(json_data)}")
# ---------------------------------------
json_data = extract_excel_fields(
file_path=PATH_BASE + r"sabt/طرح های دوره دهم.xlsx",
fields=[],
sheet_name="Export",
)
save_orjson(
data=json_data,
path=PATH_BASE + f"sabt/tarh_10.json",
)
print(f"tarh_10 {len(json_data)}")
# ---------------------------------------
json_data = extract_excel_fields(
file_path=PATH_BASE + r"sabt/طرح های دوره یازدهم.xlsx",
fields=[],
sheet_name="Export",
)
save_orjson(
data=json_data,
path=PATH_BASE + f"sabt/tarh_11.json",
)
print(f"tarh_11 {len(json_data)}")
# ---------------------------------------
json_data = extract_excel_fields(
file_path=PATH_BASE + r"sabt/طرح های دوره دوازدهم.xlsx",
fields=[],
sheet_name="Export",
)
save_orjson(
data=json_data,
path=PATH_BASE + f"sabt/tarh_12.json",
)
print(f"tarh_12 {len(json_data)}")
def create_map_tarh_json(
file_excel="1.daftar sabt parvandeha1_clean.xlsx",
file_out="result/map_tarh_9101112.json",
):
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=PATH_BASE + file_excel,
fields=["شماره ثبت", "شماره پرونده"],
sheet_name=str(u),
)
_number_of_sabt = 0
_number_of_parvande = 0
for i in json_data:
sabt = split_object_m2m(str(i["شماره ثبت"]).replace(".", "/"))
parvande = split_object_m2m(str(i["شماره پرونده"]).replace(".", "/"))
_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=PATH_BASE + file_out,
)
def proccess_main():
map_all_tarh = load_orjson(PATH_BASE + "result/map_tarh_9101112.json")
all_map_data = load_orjson(PATH_BASE + "result/all_map_full_data.json")
tarh_9 = load_orjson(PATH_BASE + r"sabt\tarh_9.json")
tarh_10 = load_orjson(PATH_BASE + r"sabt\tarh_10.json")
tarh_11 = load_orjson(PATH_BASE + r"sabt\tarh_11.json")
tarh_12 = load_orjson(PATH_BASE + r"sabt\tarh_12.json")
dict_all_map_data = {}
for i in all_map_data:
if i["شماره پرونده"] :
try:
key = i["شماره پرونده"][0].replace(".", "/")
dict_all_map_data[key] = {
"شماره ثبت وسطی": " و ".join(i["شماره ثبت"]),
"شماره شناسه وسطی": i["شماره شناسه"],
"شماره پرونده وسطی": " و ".join(i["شماره پرونده"]),
}
except:
print(' all_map_data error : ')
print(i["شماره پرونده"])
print(f"map_all_tarh {len(map_all_tarh)}")
dict_map_tarh = {}
for i in map_all_tarh :
if i["شماره پرونده"] :
key = i["شماره پرونده"][0].replace(".", "/")
dict_map_tarh[key]=i["شماره ثبت"]
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
try :
item2_s = item2.replace('.', '/').split('/')
priority = int(item2_s[0])
if high_priority < priority:
high_priority = priority
priority_data = item2
except :
pass
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)}")
f_data = load_orjson(PATH_BASE + "result/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
dict_data_sabt = {}
for item in filtered_data:
if not item["شماره عمومی"] :
continue
number_all = int(item["شماره عمومی"])
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)
dict_data_sabt[number_all] = item
print(f"valid {valid}")
save_excel(
data=filtered_data,
file_path=PATH_BASE + r"result/finall_finall.xlsx",
)
save_orjson(
path=PATH_BASE + "result/final_sabt.json",
data=dict_data_sabt
)
####################### روش دوم و نهایی ذخیره در یک فایل ##################################
##---- 1
## استخراج داده های اکسل ها در جیسون
# excel_sabt_vaset_to_json(file_excel=PATH_BASE+"1.daftar sabt parvandeha1_clean.xlsx", file_out = PATH_BASE +"result/all_map_full_data.json")
# excel_sabt_info_to_json() # tarh_9.json , ...
# create_map_tarh_json(file_excel = '1.daftar sabt parvandeha1_clean.xlsx', file_out="result/map_tarh_9101112.json")
proccess_main()
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
"""
@@ -0,0 +1,561 @@
import pandas as pd
import os
import re
from tqdm import tqdm
import unicodedata
import logging
import uuid
import traceback
from dotenv import load_dotenv
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.text_normalizer import TextNormalizer
# from general import *
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
PATH_BASE = "./data/qavanin_files/"
def validate_value(value) :
if pd.isna(value) :
return ''
value = str(value)
if value is None or '..' in value :
return ''
return value.strip(" \n")
def validate_id(value) :
value = validate_value(value)
# qq112475?ls=list
value = value.split('?')[0]
return value
#### استخراج اطلاعات از اکسل بعد انقلاب به فایل جیسون mj_qa_qanon
def extract_json_of_excel_after(elastic, path_file, index_name_o, duplicate_list, dict_sabt_info):
bulk_data_import=[]
bulk_data_update=[]
total_count = 0
row_index = 0
dict_id={}
id = ""
data_errors = []
prev_percent = 0
try:
data = excel_to_json(path_file, None, 1)
print('*' * 20 , ' count=', len(data))
cols = [
"شماره عمومی",
"شماره رديف",
"شماره پرونده",
"دوره قانونگذاری",
"عنوان",
"تاریخ تصویب",
"مرجع تصویب",
"تاریخ تایید",
"وضعيت",
"شماره روزنامه رسمی کشور",
"تاریخ انتشار روزنامه رسمی کشور",
"شماره شناسه قانون",
"شماره پرونده های مرتبط",
"اصلی/تبعی",
"مستندات",
" تصدیق کنندگان فایل word قانون با pdf",
"توضیحات تصدیق",
"تاریخ لازم الاجرا شدن",
" تطبیق کنندگان فایلpdf با روزنامه رسمی",
"توضیحات تطبیق فایلpdf با روزنامه رسمی",
"_id",
"error",
"وجود فایل",
"تطابق با الگو",
"مدیریت خطا",
"مسیر",
"فایلها"
]
text_normalizer = TextNormalizer()
total = len(data)
row_index = 0
for item in data:
row_index += 1
percent = int((row_index / total) * 100)
if percent != prev_percent:
print("progress -> %.2f %%" % percent)
prev_percent = percent
error_files_state = item.get("مدیریت خطا", "")
title = item.get("عنوان", "").strip(" \n")
title = text_normalizer.normalize_qanon(title)
_id = validate_id(item.get("_id", ""))
davam_type = ''
eid = _id
number_all = validate_value(item.get("شماره عمومی", ""))
if number_all :
number_all = str(int(float(number_all))) # 288.0 -> 288
number_row_duplicate = validate_value(item.get('شماره رديف', ""))
if number_row_duplicate :
number_row_duplicate = str(int(float(number_row_duplicate)))
number_row = validate_value(item.get("شماره پرونده", ""))
ts_date = validate_value(item.get("تاریخ تصویب", ""))
ts_date, err_msg = convert_persian_date(ts_date)
ts_ref = validate_value(item.get("مرجع تصویب", "")) # ????? ts_ref
ts_ref = text_normalizer.normalize_qanon(ts_ref)
shora_date = validate_value(item.get("تاریخ تایید", ""))
shora_date, err_msg = convert_persian_date(shora_date)
exec_date = item.get("تاریخ لازم الاجرا شدن", "")
exec_date, err_msg = convert_persian_date(exec_date)
rrk_number = validate_value(item.get("شماره روزنامه رسمی کشور", ""))
rrk_date = item.get("تاریخ انتشار روزنامه رسمی کشور", "")
rrk_date, err_msg = convert_persian_date(rrk_date)
# number_qanon = item.get("شماره شناسه قانون", "") ? ////?????
description = item.get("مستندات", "")
description = text_normalizer.normalize_qanon(description)
term = validate_value(item.get("دوره قانونگذاری", "")) # ???? term
term = text_normalizer.normalize_qanon(term)
qanon_etebar = validate_value(item.get("وضعيت", ""))
qanon_etebar = text_normalizer.normalize_qanon(qanon_etebar)
path_file = validate_value(item.get("مسیر", ""))
name_files = validate_value(item.get("فایلها", ""))
# title = item.get("شماره پرونده های مرتبط", "") # فیلد معادل ندارد - تبعی های مرتبط و مثل این منظورهست که خودکار پر میشود یا سامانه می دهد
# title = item.get("اصلی/تبعی", "") # فیلد معادل ندارد
# title = item.get("بررسی کننده", "") # فیلد معادل ندارد
# title = item.get("تایید نهایی", "") # فیلد معادل ندارد
main_type='قانون'
sub_type = 'عادی'
number = {}
if number_all :
number["all"] = number_all
if number_row_duplicate :
number["row_duplicate"] = number_row_duplicate
if number_row :
number["row"] = number_row
letters = []
if shora_date :
letters.append({
"type" : "تایید شورای نگهبان",
"date" : shora_date
})
if rrk_number or rrk_date :
r_item = {
"type" : "انتشار در روزنامه رسمی",
"number" : rrk_number
}
if rrk_date :
r_item["date"] = rrk_date
letters.append(r_item)
eid = _id
is_update = True
if not _id.startswith('qq') :
try:
if _id.startswith('qs'):
res = elastic.get_document("mj_qa_section", _id)
if "_source" in res and "qanon_id" in res["_source"]:
eid = res["_source"]["qanon_id"]
is_update = True
if not eid.startswith('qq') :
query = {
"term": {
"number.all": {
"value": number_all
}
}
}
es_res = elastic.search( index="mj_qa_qanon",query=query)
es_res = es_res["hits"]["hits"]
if len(es_res) == 1:
eid = es_res[0]['_id']
is_update = True
elif len(es_res) > 1:
data_errors.append({"row":row_index, "message": "search number_all is > 1", "number_all": number_all})
continue
else:
is_update= False
eid='qe_'+ uuid.uuid4().hex[:8]
sub_type='نامشخص'
except Exception as e:
data_errors.append({"row":row_index, "message": str(e), "number_all": number_all})
continue
files_info=[]
for name in name_files.split(','):
if not name :
continue
file_type = ''
if name.endswith(".pdf"):
file_type="pdf"
elif name.endswith(
(".jpg", ".jpeg", ".png", ".tif", ".bmp")
):
file_type="img"
else :
file_type=""
files_info.append({
"path": os.path.join(path_file, name),
"file_name": name,
"title": name,
"type": file_type
})
data = {
"id": eid,
"title": title,
"main_type": main_type,
"sub_type": sub_type,
"term": term,
"description": description
}
if qanon_etebar :
data["qanon_etebar"] = qanon_etebar
if ts_ref :
data["ts_ref"] = ts_ref
if path_file :
data["path_file"] = path_file
if files_info :
data["files"] = files_info
if number :
data["number"] = number
if letters :
data["letters"] = letters
if ts_date :
data["ts_date"] = ts_date
data["sort_date_timestamp"] = dateTimestamp(ts_date)
if exec_date :
data["exec_date"] = exec_date
if eid in duplicate_list :
duplicate_list[eid]["duplcate2"] = { "excel":"after", "row2": str(row_index), "is_update_row2": is_update}
continue
if eid in dict_id :
duplicate_list[eid] = { "excel":"after", "type_duplicate":"inner", "id":eid, "row1": dict_id[eid], "row2": str(row_index), "is_update_row2": is_update}
continue
#--------------------------
if number_all in dict_sabt_info :
sabt_info = dict_sabt_info[number_all]
# "ردیف": "۴۹۴",
# "شماره ثبت": "۱۹۷",
# "عنوان طرح/ لایحه": "طرح استفساريه در مورد رسميت يافتن جلسه هيأت حل اختلاف موضوع ماده(۷۹) قانون تشكيلات، وظايف و انتخابات شوراهاي اسلامي كشور و انتخاب شهرداران",
# "نوع طرح / لایحه": "طرح نمایندگان",
# "تاریخ تقدیم": "۱۳۹۵/۰۷/۱۹",
# "طراح مسئول": "احمد امیرآبادی فراهانی - ۱۰۰۲۶",
# "تعداد امضا": "۲۳",
# "فوریت پیشنهادی": "عادی",
# "فوریت مصوب": "عادی",
# "شماره پیش طرح": "۰",
# "شماره ثبت وسطی": "10/197",
# "شماره شناسه وسطی": "1395081202",
# "شماره پرونده وسطی": "10/4751"
initial = {}
decription = ""
if "عنوان طرح/ لایحه" in sabt_info :
initial["title"] = sabt_info["عنوان طرح/ لایحه"].strip()
if "ردیف" in sabt_info :
decription += "ردیف" + ":" + sabt_info["ردیف"] + "\n"
if "شماره ثبت" in sabt_info :
decription += "شماره ثبت" + ":" + sabt_info["شماره ثبت"] + "\n"
if "نوع طرح / لایحه" in sabt_info :
initial["plan_type"] = sabt_info["نوع طرح / لایحه"].strip()
if "تاریخ تقدیم" in sabt_info :
plan_date, err_msg = convert_persian_date(sabt_info["تاریخ تقدیم"])
if plan_date:
initial["plan_date"] = plan_date
if "طراح مسئول" in sabt_info :
initial["plan_signer"] = sabt_info["طراح مسئول"].strip()
if "تعداد امضا" in sabt_info :
decription += "تعداد امضا" + ":" + sabt_info["تعداد امضا"] + "\n"
if "فوریت پیشنهادی" in sabt_info :
decription += "فوریت پیشنهادی" + ":" + sabt_info["فوریت پیشنهادی"].strip() + "\n"
if "فوریت مصوب" in sabt_info :
decription += "فوریت مصوب" + ":" + sabt_info["فوریت مصوب"].strip() + "\n"
if "شماره پیش طرح" in sabt_info :
decription += "شماره پیش طرح" + ":" + str(sabt_info["شماره پیش طرح"]) + "\n"
if "شماره ثبت وسطی" in sabt_info :
decription += "شماره ثبت وسطی" + ":" + str(sabt_info["شماره ثبت وسطی"]) + "\n"
if "شماره شناسه وسطی" in sabt_info :
decription += "شماره شناسه وسطی" + ":" + str(sabt_info["شماره شناسه وسطی"]) + "\n"
if "شماره پرونده وسطی" in sabt_info :
decription += "شماره پرونده وسطی" + ":" + str(sabt_info["شماره پرونده وسطی"]) + "\n"
if decription :
initial["decription"] = decription
if initial :
data["initial"] = initial
#--------------------------
dict_id[eid] = str(row_index)
if is_update :
bulk_data_update.append({
"_id": eid,
"_source": data
})
else :
bulk_data_import.append({
"_id": eid,
"_source": data
})
# if len(bulk_data_update) >= 100:
# total_count += len(bulk_data_update)
# print('=' * 10, ' update , total='+str(total_count) , str(row_index))
# elastic.updateBulkList(bulk_data_update, index_name_o, True)
# bulk_data_update = []
# if len(bulk_data_import) >= 100:
# total_count += len(bulk_data_import)
# print('=' * 10, ' import , total='+str(total_count) , str(row_index))
# elastic.importBulkList(bulk_data_import, index_name_o, True)
# bulk_data_import = []
# if len(bulk_data_update):
# total_count += len(bulk_data_update)
# print('=' * 10, ' update , total='+str(total_count) , str(row_index))
# elastic.updateBulkList(bulk_data_update, index_name_o, True)
# bulk_data_update = []
# if len(bulk_data_import):
# total_count += len(bulk_data_import)
# print('=' * 10, ' import , total='+str(total_count) , str(row_index))
# elastic.importBulkList(bulk_data_import, index_name_o, True)
# bulk_data_import = []
elastic.es.indices.refresh(index=index_name_o)
print(elastic.es.cat.count(index=index_name_o, format="json"))
except Exception as e:
print("Exception: " + str(e))
traceback.print_exc()
file_log1= "result/after_error.json"
with open(PATH_BASE + file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(data_errors, ensure_ascii=False, indent=4))
return bulk_data_update, bulk_data_import
def create_final_json_qaqanon(elastic):
file_duplicate_prev = PATH_BASE + "result/duplicate_tasmim.json"
file_duplicate = PATH_BASE + "result/duplicate_tasmim_sabt.json"
file_excel = PATH_BASE + r"qavanin_output5.xlsx"
file_sabr_info = PATH_BASE + "result/final_sabt.json"
dict_sabt_info = {}
with open(file_sabr_info, 'r', encoding='utf8') as f :
dict_sabt_info = json.loads( f.read())
duplicate_list = {}
with open(file_duplicate_prev, 'r', encoding='utf8') as f :
duplicate_list = json.loads( f.read())
bulk_data_update, bulk_data_import = extract_json_of_excel_after(elastic, file_excel, "mj_qa_qanon", duplicate_list, dict_sabt_info)
with open(file_duplicate, 'w', encoding='utf8') as f :
json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
file = PATH_BASE + "result/data_for_update.json"
with open(file, 'w', encoding='utf8') as f :
json.dump(bulk_data_update, f, ensure_ascii=False, indent=4)
file = PATH_BASE + "result/data_for_import.json"
with open(file, 'w', encoding='utf8') as f :
json.dump(bulk_data_import, f, ensure_ascii=False, indent=4)
def update_json_to_qaqanon(elastic, file_json, index_name_o="mj_qa_qanon"):
data_json = []
with open(file_json, 'r', encoding='utf8') as f :
data_json = json.loads( f.read())
bulk_data_update=[]
total_count = 0
row_index = 0
dict_id={}
id = ""
data_errors = []
prev_percent = 0
total = len(data_json)
for item in data_json :
row_index += 1
percent = int((row_index / total) * 100)
if percent != prev_percent:
print("progress -> %.2f %%" % percent)
prev_percent = percent
eid = item["_id"]
source = {}
try:
res = elastic.get_document(index_name_o, eid)
source = res["_source"]
except Exception as e:
continue
new_source = item["_source"]
data = {}
letters = []
if "letters" in source :
letters = source["letters"]
if "letters" in new_source :
letters.append(new_source["letters"])
data["letters"] = letters
if "term" in new_source :
data["term"] = new_source["term"]
if "path_file" in new_source :
data["path_file"] = new_source["path_file"]
if "files" in new_source :
data["files"] = new_source["files"]
if "number" in new_source :
data["number"] = new_source["number"]
if "exec_date" in new_source :
data["exec_date"] = new_source["exec_date"]
if "initial" in new_source :
data["initial"] = new_source["initial"]
bulk_data_update.append({
"_id": eid,
"_source": data
})
if len(bulk_data_update) >= 100:
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(row_index))
elastic.updateBulkList(bulk_data_update, index_name_o, True)
bulk_data_update = []
if len(bulk_data_update):
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(row_index))
elastic.updateBulkList(bulk_data_update, index_name_o, True)
bulk_data_update = []
def import_json_to_qaqanon(elastic, file_json, index_name_o="mj_qa_qanon"):
data_json = []
with open(file_json, 'r', encoding='utf8') as f :
data_json = json.loads( f.read())
bulk_data_import=[]
total_count = 0
row_index = 0
dict_id={}
id = ""
data_errors = []
prev_percent = 0
total = len(data_json)
for item in data_json :
row_index += 1
percent = int((row_index / total) * 100)
if percent != prev_percent:
print("progress -> %.2f %%" % percent)
prev_percent = percent
eid = item["_id"]
new_source = item["_source"]
data = new_source
bulk_data_import.append({
"_id": eid,
"_source": data
})
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' update , total='+str(total_count) , str(row_index))
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' update , total='+str(total_count) , str(row_index))
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
###------------------------------------------
###------------------------------------------
load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
print(".... majles_codes_update_steps ......", host)
path_base_map = "G:/Project2/gateway_php/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
###------------------------------------------
###------------------------------------------
# create_final_json_qaqanon(elastic)
# file = PATH_BASE + "result/data_for_update.json"
# update_json_to_qaqanon(elastic, file)
# file = PATH_BASE + "result/data_for_import.json"
# import_json_to_qaqanon(elastic, file)
# # # #------------------------------------------
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon")
+36 -31
View File
@@ -92,6 +92,37 @@ def update_mj_qa_rules_with_rule_relations():
}
def get_evaluation_data(data: E):
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 update_mj_qa_rules_with_4plan_data(
index_schema_path=r"D:\init_mahdi\dataParsers\schema\mj_qa_rule.json",
version_key="pair_gvc_e1_jv3_all",
@@ -110,35 +141,7 @@ def update_mj_qa_rules_with_4plan_data(
get_index_name="mj_qa_rule",
out_put_index_name="mj_qa_conflict",
):
def get_evaluation_data(data: E):
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_vlide_text(text):
if text == "valid":
return "معتبر"
elif text == "invalid":
return "نامعتبر"
elif text == "undetermined":
return "نامشخص"
map_sec_id_full_path = {}
for i in DataHelper.load_orjson(r"D:\init_mahdi\dataParsers\mj_qa_section.json"):
try:
@@ -253,8 +256,8 @@ def update_mj_qa_rules_with_4plan_data(
"description": item.evaluation.comments,
},
"conflict_final": {
"valid_state1": get_vlide_text(item.final_validity.section1_validity),
"valid_state2": get_vlide_text(item.final_validity.section2_validity),
"valid_state1": get_vlid_text(item.final_validity.section1_validity),
"valid_state2": get_vlid_text(item.final_validity.section2_validity),
"description": item.final_validity.evaluator_comments,
},
}
@@ -272,13 +275,15 @@ def update_mj_qa_rules_with_4plan_data(
print("=" * 10, "to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, out_put_index_name)
bulk_data = []
print(f"failed_data {len(failed_data)}")
DataHelper.save_orjson(
data=failed_data,
path=r"D:\init_mahdi\dataParsers\failed_data_mj_qa_conflict.json",
)
update_mj_qa_rules_with_4plan_data()
# python -m dataParsers.app.update_mj_qa_rules