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
@@ -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 = [
@@ -662,4 +662,8 @@ def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o, duplicate
print("Exception: " + str(e))
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")