From 8f63d947f34145546e92fef433b10818d5faee9d Mon Sep 17 00:00:00 2001 From: hsafaei Date: Wed, 23 Jul 2025 08:56:51 +0330 Subject: [PATCH] 1 --- qanon_functions.py | 282 ++++++++++++++++++++++++++++++++++++++ r3_import_excel_tcodes.py | 273 +----------------------------------- r6_before_excel.py | 50 +++++++ 3 files changed, 333 insertions(+), 272 deletions(-) create mode 100644 qanon_functions.py create mode 100644 r6_before_excel.py diff --git a/qanon_functions.py b/qanon_functions.py new file mode 100644 index 0000000..e44ed60 --- /dev/null +++ b/qanon_functions.py @@ -0,0 +1,282 @@ +import os +import re +import traceback +import json +from dotenv import load_dotenv +from config_base import * +# from general_functions import * +from text_normalizer import TextNormalizer +from elastic_helper import ElasticHelper +# from excel_helper import ExcelHelper +import pandas as pd + +text_normalizer = TextNormalizer() + +def is_nan_or_none_or_empty(value): + """ + Checks if a value is NaN, None, or an empty string. + + Args: + value: The value to check. + + Returns: + True if the value is NaN, None, or an empty string, False otherwise. + """ + if value is None: + return True + if isinstance(value, str) and value == "": + return True + if isinstance(value, float) : + return True + if pd.isna(value): + return True + return False + + +def get_qanon_title_sample(text): + + spell_list = [ + "ائین‌نامه[آئین نامه]=آئین نامه", + "انگیس[انگلیس]=انگلیس", + "انگیس=انگلیس", + "ائین‌نامه=آئین نامه", + "بوزارت=به وزارت" + "تهرات=تهران" + ] + + + text = text_normalizer.date_correction(text) + text = text_normalizer.word_digit_correction(text) + text = text_normalizer.hamzah_normal(text) + text = text_normalizer.alaem_normal(text) + text = re.sub(r"( |\u200C)+", "", text) + + if text.startswith('فصل'): + # در آدرس دهی چون براساس شماره ماده هست فصل مهم نیست. چون شماره ماده کلی هست + text = re.sub(r"^(فصل[^>]>)+", "", text) + return text + +def get_section_title_sample(text): + text = text_normalizer.normalize_search_qanon(text) + text = text_normalizer.remove_arabic_diacritics(text) + text = text_normalizer.hamzah_normal(text) + text = text_normalizer.alaem_normal(text) + text = re.sub(r"( |\u200C|\>|\<|-|ـ)+", "", text) + return text + +def searchSectionId(elastic, index_name, qanon_id, section_title): + score = 100 + body = { + "query": { + "bool": { + "must": [ + { + "term": { + "qanon_id": { + "value": qanon_id + } + } + + }, + { + "match": { + "other_info.full_path": section_title + } + } + ] + } + } + } + s_res = elastic.es.search(index=index_name, body=body) + section_title = get_section_title_sample(section_title) + for item in s_res["hits"]["hits"]: + other_info = item['_source']['other_info'] + title = other_info['full_path'] + # حذف اضافات + title = get_section_title_sample(title) + + if title == section_title : + return item["_id"], 100, item + + return 0, 0, {} + +def get_dict_qanon_title(file_path): + dict = {} + with open(file_path, 'r', encoding='utf8') as file1: + for line in file1.readlines() : + items = line.split('=') + if len(items) == 2 : + dict[items[0]] = items[1] + return dict + + +def searchQanonId(elastic, index_name, qanon_title, ts_data=""): + score = 100 + body = { + "query": { + "bool": { + "must": [ + { + "term": { + "title.keyword": { + "value": qanon_title + } + } + } + ] + } + } + } + s_res = elastic.es.search(index=index_name, body=body) + total = s_res["hits"]["total"]['value'] + if total == 1 : + item = s_res["hits"]["hits"][0] + return item["_id"], score, item + + if total == 0 : + body = { + "query": { + "more_like_this": { + "fields": [ + "title.fa" + ], + "like": qanon_title, + "min_term_freq": 1, + "max_query_terms": 12 + } + } + } + s_res = elastic.es.search(index=index_name, body=body) + total = s_res["hits"]["total"]['value'] + + qanon_title_sample = re.sub(r"( |\u200C)+", "", qanon_title) + list_equal = [] + for item in s_res["hits"]["hits"]: + title = item['_source']['title'] + # حذف اسپیسها + title_sample = re.sub(r"( |\u200C)+", "", title) + + if title_sample == qanon_title_sample : + list_equal.append(item) + else : + qanon_title_sample = get_qanon_title_sample(qanon_title) + + title_sample = get_qanon_title_sample(title) + + if title_sample == qanon_title_sample : + list_equal.append(item) + + if len(list_equal) == 1 : + item = list_equal[0] + score = 90 + if ts_data == item['_source']['ts_date'] : + score = 100 + return item["_id"], score, item + + for item in list_equal : + if ts_data == item['_source']['ts_date'] : + score = 100 + return item["_id"], score, item + + if len(list_equal) : + score = 90 + item = list_equal[0] + return item["_id"], score, item + + return 0, 0, {} + + +def get_qanon_date(title): + # regex = r"مصوب(\s*\d{1,4}/\d{1,4}/\d{1,4})\s*$" + regex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$" + regex_ex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|کمیسیونهای|هیات|شورای).{1,50})$" + ts_ref = '' + qanon_title = '' + ts_date = '' + title=title.strip().strip(' #=').strip() + title=title.replace("=", "#") + title=title.replace("#مصوب#", "#مصوب ") + title=title.replace("#مصوب #", "#مصوب ") + items = title.split('#') + if len(items) == 1: + qanon_title = items[0] + elif items : + last = items[-1].strip() + if last.startswith('مصوب'): + ts_date = last.replace('مصوب', '').strip() + qanon_title= ' '.join(items[:-1]) + # قانون تشكيل#وزارت جهاد سازندگي مصوب 08/09/1362 مجلس شوراي اسلامي + elif 'مصوب' in last : + qanon_title= ' '.join(items) + elif last : + ts_ref=last + qanon_title= ' '.join(items[:-1]) + + # print('qanon_title', qanon_title) + + + if ts_date == '' : + # قانون كار مصوب 26/12/1337 + match = re.search(regex, qanon_title) + if match : + #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") + ts_date = match.group(1).strip() + qanon_title = qanon_title[0:match.start()] + + if ts_date == '': + match = re.search(regex_ex, qanon_title) + if match : + #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") + ts_date = match.group(1).strip() + ts_ref = match.group(2).strip() + qanon_title = qanon_title[0:match.start()] + + + return qanon_title, ts_date, ts_ref + +def get_section_correct(title): + title=title.strip().strip(' #=').strip() + + if title == 'کل قانون' or title == 'متن قانون' or title == 'متن' or title == 'تمام قانون' or title == 'کل مصوبه': + return ['all'] + + title=title.replace('"', '') + title=title.replace('اصلاحی', '') + title = re.sub(r"(\(|\)|\>|\<|-|ـ)+", "", title) + + subs = title.split('،') + result = [] + for item in subs : + item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)", r"#\1", item) + items = item.split('#') + items.reverse() + item = '> '.join(items).strip(' >').replace(' ', '') + item = text_normalizer.word_digit_correction(item) + result.append(item) + + return result + + +def get__all_section_qanon(elastic, index_name, qanon_id): + body = { + "_source" : ["ref_id"], + "query": { + "bool": { + "must": [ + { + "term": { + "qanon_id": { + "value": qanon_id + } + } + } + ] + } + } + } + s_res = elastic.es.search(index=index_name, body=body) + result = [] + for item in s_res["hits"]["hits"] : + result.append(item["_id"]) + return result + diff --git a/r3_import_excel_tcodes.py b/r3_import_excel_tcodes.py index de760ef..e1f9c45 100644 --- a/r3_import_excel_tcodes.py +++ b/r3_import_excel_tcodes.py @@ -5,186 +5,10 @@ import json from dotenv import load_dotenv from config_base import * # from general_functions import * -from text_normalizer import TextNormalizer from elastic_helper import ElasticHelper # from excel_helper import ExcelHelper import pandas as pd - -text_normalizer = TextNormalizer() - -def is_nan_or_none_or_empty(value): - """ - Checks if a value is NaN, None, or an empty string. - - Args: - value: The value to check. - - Returns: - True if the value is NaN, None, or an empty string, False otherwise. - """ - if value is None: - return True - if isinstance(value, str) and value == "": - return True - if isinstance(value, float) : - return True - if pd.isna(value): - return True - return False - - -def get_qanon_title_sample(text): - - spell_list = [ - "ائین‌نامه[آئین نامه]=آئین نامه", - "انگیس[انگلیس]=انگلیس", - "انگیس=انگلیس", - "ائین‌نامه=آئین نامه", - "بوزارت=به وزارت" - "تهرات=تهران" - ] - - - text = text_normalizer.date_correction(text) - text = text_normalizer.word_digit_correction(text) - text = text_normalizer.hamzah_normal(text) - text = text_normalizer.alaem_normal(text) - text = re.sub(r"( |\u200C)+", "", text) - - if text.startswith('فصل'): - # در آدرس دهی چون براساس شماره ماده هست فصل مهم نیست. چون شماره ماده کلی هست - text = re.sub(r"^(فصل[^>]>)+", "", text) - return text - -def get_section_title_sample(text): - text = text_normalizer.normalize_search_qanon(text) - text = text_normalizer.remove_arabic_diacritics(text) - text = text_normalizer.hamzah_normal(text) - text = text_normalizer.alaem_normal(text) - text = re.sub(r"( |\u200C|\>|\<|-|ـ)+", "", text) - return text - -def searchSectionId(elastic, index_name, qanon_id, section_title): - score = 100 - body = { - "query": { - "bool": { - "must": [ - { - "term": { - "qanon_id": { - "value": qanon_id - } - } - - }, - { - "match": { - "other_info.full_path": section_title - } - } - ] - } - } - } - s_res = elastic.es.search(index=index_name, body=body) - section_title = get_section_title_sample(section_title) - for item in s_res["hits"]["hits"]: - other_info = item['_source']['other_info'] - title = other_info['full_path'] - # حذف اضافات - title = get_section_title_sample(title) - - if title == section_title : - return item["_id"], 100, item - - return 0, 0, {} - -def get_dict_qanon_title(file_path): - dict = {} - with open(file_path, 'r', encoding='utf8') as file1: - for line in file1.readlines() : - items = line.split('=') - if len(items) == 2 : - dict[items[0]] = items[1] - return dict - - -def searchQanonId(elastic, index_name, qanon_title, ts_data=""): - score = 100 - body = { - "query": { - "bool": { - "must": [ - { - "term": { - "title.keyword": { - "value": qanon_title - } - } - } - ] - } - } - } - s_res = elastic.es.search(index=index_name, body=body) - total = s_res["hits"]["total"]['value'] - if total == 1 : - item = s_res["hits"]["hits"][0] - return item["_id"], score, item - - if total == 0 : - body = { - "query": { - "more_like_this": { - "fields": [ - "title.fa" - ], - "like": qanon_title, - "min_term_freq": 1, - "max_query_terms": 12 - } - } - } - s_res = elastic.es.search(index=index_name, body=body) - total = s_res["hits"]["total"]['value'] - - qanon_title_sample = re.sub(r"( |\u200C)+", "", qanon_title) - list_equal = [] - for item in s_res["hits"]["hits"]: - title = item['_source']['title'] - # حذف اسپیسها - title_sample = re.sub(r"( |\u200C)+", "", title) - - if title_sample == qanon_title_sample : - list_equal.append(item) - else : - qanon_title_sample = get_qanon_title_sample(qanon_title) - - title_sample = get_qanon_title_sample(title) - - if title_sample == qanon_title_sample : - list_equal.append(item) - - if len(list_equal) == 1 : - item = list_equal[0] - score = 90 - if ts_data == item['_source']['ts_date'] : - score = 100 - return item["_id"], score, item - - for item in list_equal : - if ts_data == item['_source']['ts_date'] : - score = 100 - return item["_id"], score, item - - if len(list_equal) : - score = 90 - item = list_equal[0] - return item["_id"], score, item - - return 0, 0, {} - +from qanon_functions import * def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): # excel_helper = ExcelHelper() @@ -361,101 +185,6 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i with open(file_log2, 'w', encoding='utf8') as file2: file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4)) - -def get_qanon_date(title): - # regex = r"مصوب(\s*\d{1,4}/\d{1,4}/\d{1,4})\s*$" - regex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$" - regex_ex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|کمیسیونهای|هیات|شورای).{1,50})$" - ts_ref = '' - qanon_title = '' - ts_date = '' - title=title.strip().strip(' #=').strip() - title=title.replace("=", "#") - title=title.replace("#مصوب#", "#مصوب ") - title=title.replace("#مصوب #", "#مصوب ") - items = title.split('#') - if len(items) == 1: - qanon_title = items[0] - elif items : - last = items[-1].strip() - if last.startswith('مصوب'): - ts_date = last.replace('مصوب', '').strip() - qanon_title= ' '.join(items[:-1]) - # قانون تشكيل#وزارت جهاد سازندگي مصوب 08/09/1362 مجلس شوراي اسلامي - elif 'مصوب' in last : - qanon_title= ' '.join(items) - elif last : - ts_ref=last - qanon_title= ' '.join(items[:-1]) - - # print('qanon_title', qanon_title) - - - if ts_date == '' : - # قانون كار مصوب 26/12/1337 - match = re.search(regex, qanon_title) - if match : - #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") - ts_date = match.group(1).strip() - qanon_title = qanon_title[0:match.start()] - - if ts_date == '': - match = re.search(regex_ex, qanon_title) - if match : - #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") - ts_date = match.group(1).strip() - ts_ref = match.group(2).strip() - qanon_title = qanon_title[0:match.start()] - - - return qanon_title, ts_date, ts_ref - -def get_section_correct(title): - title=title.strip().strip(' #=').strip() - - if title == 'کل قانون' or title == 'متن قانون' or title == 'متن' or title == 'تمام قانون' or title == 'کل مصوبه': - return ['all'] - - title=title.replace('"', '') - title=title.replace('اصلاحی', '') - title = re.sub(r"(\(|\)|\>|\<|-|ـ)+", "", title) - - subs = title.split('،') - result = [] - for item in subs : - item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)", r"#\1", item) - items = item.split('#') - items.reverse() - item = '> '.join(items).strip(' >').replace(' ', '') - item = text_normalizer.word_digit_correction(item) - result.append(item) - - return result - -def get__all_section_qanon(elastic, index_name, qanon_id): - body = { - "_source" : ["ref_id"], - "query": { - "bool": { - "must": [ - { - "term": { - "qanon_id": { - "value": qanon_id - } - } - } - ] - } - } - } - s_res = elastic.es.search(index=index_name, body=body) - result = [] - for item in s_res["hits"]["hits"] : - result.append(item["_id"]) - return result - - def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): df = pd.read_excel(file_excel, sheet_name=0) diff --git a/r6_before_excel.py b/r6_before_excel.py new file mode 100644 index 0000000..f871320 --- /dev/null +++ b/r6_before_excel.py @@ -0,0 +1,50 @@ +import os +import re +import traceback +import json +from dotenv import load_dotenv +from config_base import * +from elastic_helper import ElasticHelper +import pandas as pd +from qanon_functions import * + + +def importBeforeInfosToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): + df = pd.read_excel(file_excel, sheet_name=0, header=None) + count = 0 + rows_list = df.to_dict(orient='records') + total = len(df[0]) + print('total : ', total) + + column_names = df.columns.tolist() + print(column_names) + + file = open(file_log, 'w+', encoding='utf8') + + dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt") + # Print the list of rows + dic_error_qanon_title={} + dic_error_section_title={} + rows_list_new = [] + bulk_data = [] + total_count=0 + + +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(password) + +path_base_map = "G:/Project2/gateway2_main/repo/_other/" +elastic = ElasticHelper(host, password, "elastic", path_base_map) + + +#importBeforeInfosToElastic(elastic, "./data/tcodes", "./data/tcodes/result") \ No newline at end of file