diff --git a/1_errors.txt b/1_errors.txt new file mode 100644 index 0000000..bc7ca1c --- /dev/null +++ b/1_errors.txt @@ -0,0 +1,150 @@ + + id : 7146684233a18337 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.072893 + +************************************************** + + id : 5786684233a599bb + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.091862 + +************************************************** + + id : 6296684233a65bf6 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.105075 + +************************************************** + + id : 1846684233a1833d + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.117742 + +************************************************** + + id : 4236684233a1833c + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.126099 + +************************************************** + + id : 8996684233a65bf4 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.138489 + +************************************************** + + id : 1336684233a32c6b + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.157003 + +************************************************** + + id : 2606684233a25dda + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.179001 + +************************************************** + + id : 6076684233a4dc06 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.189007 + +************************************************** + + id : 5926684233a599c5 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.200010 + +************************************************** + + id : 1996684233a65bf7 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.208003 + +************************************************** + + id : 4906684233a7f0bb + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.216003 + +************************************************** + + id : 5526684233a599c3 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.223002 + +************************************************** + + id : 8126684233a599c2 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.232022 + +************************************************** + + id : 3436684233a599c1 + filename : G:\Project2\NLP\SqlToElasticMajles\.env\Lib\site-packages\elasticsearch\_sync\client\_base.py + function : _perform_request + err line no : 352 + err line : raise HTTP_EXCEPTIONS.get(meta.status, ApiError)( + err message : BadRequestError(400, 'illegal_argument_exception', 'mapper [result_objects.values.score] cannot be changed from type [text] to [long]') + err date : 2025-02-15 19:58:40.240002 + +************************************************** diff --git a/concatenace_json.py b/concatenace_json.py new file mode 100644 index 0000000..4d6b7de --- /dev/null +++ b/concatenace_json.py @@ -0,0 +1,41 @@ +import json +import datetime + +from general_functions import read_file_by_address, read_from_json + +if __name__ == "__main__": + start_time = datetime.datetime.now() + print(f'start time: {start_time}') + + # inputfile = open('./data/main_classes_dataset_03.json', "r", encoding='utf-8') + # inputfile = open('./data/sections_40k_normalized.json', "r", encoding='utf-8') + # data = json.load(inputfile) + # inputfile.close() + + # prev_ids = read_file_by_address('./data/prev_kw_ids_170k.txt').splitlines() + + counter = 1 + file_counter = 1 + temp_dict = [] + temp_data_text = '' + period_sections = [] + period_ids_text = f'***** file number: {file_counter} *****\n' + + finall_sections = [] + for file_counter in range(1,41): + + # inputfile = open(f'./data/sections_kw_llama8b_170k_{str(file_counter)}.json', "a+", encoding='utf-8') + data = read_from_json(f'./data/sections_kw_llama8b_40k_{str(file_counter)}.json') + + print(f'file {file_counter} is in proccess ... ') + for item in data: + id = item['id'] + finall_sections.append(item) + + outputfile = open(f'./data/sections_kw_llama8b_40k_concatenated.json', "a+", encoding='utf-8') + outputfile.write(json.dumps(finall_sections, ensure_ascii=False, indent=2)) + outputfile.close() + + end_time = datetime.datetime.now() + print(f"end_time: {end_time}") + print("end") \ No newline at end of file diff --git a/config_base.py b/config_base.py index 008c60b..1f523dc 100644 --- a/config_base.py +++ b/config_base.py @@ -5,8 +5,7 @@ import pyodbc # و باید توکن معتبر جدید از سایت قوانین درحالت لاگین شده، # دریافت شود و به جای توکن زیر جایگزین شود -#TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzM2Njk2NjIsImp0aSI6Ik5zRDJpNDZrcDFsNHdKRU9KR2x2Vnl0ejBNenlpMmFMIiwiaXNzIjpudWxsLCJleHAiOjE3MzQ5Njk2NjEsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDYyOFx1MDYzMVx1MDY0Nlx1MDYyN1x1MDY0NVx1MDY0NyBcdTA2NDZcdTA2NDhcdTA2Y2NcdTA2MzMiLCJsYXN0X25hbWUiOiJcdTA2NDFcdTA2NDZcdTA2Y2MiLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.K5Z4150USK2WvdC7eo1v8koiR2wRN1--XY7Xf9LhMEA' -TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzY3MDAxNjksImp0aSI6IlwvYkhhWktHNmlMR0YxWTBwdk5OM3YzZ2dycUpNWHRmQyIsImlzcyI6bnVsbCwiZXhwIjoxNzM4MDAwMTY4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjEsImZpcnN0X25hbWUiOiJcdTA2NDVcdTA2MmZcdTA2Y2NcdTA2MzEgXHUwNjQxXHUwNjQ2XHUwNmNjIiwibGFzdF9uYW1lIjoiXHUwNjMzXHUwNjI3XHUwNjQ1XHUwNjI3XHUwNjQ2XHUwNjQ3IiwiZW1haWwiOiJkZXZAZ21haWwuY29tIiwidXNlcm5hbWUiOiJkZXYiLCJ1c2VyX2xldmVsIjoyfX0.lH9X9ACG2rzTWPyrYdxZFzmAUBr2qG0KQJoCZ7wN-rs' +TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3Mzk3ODc1NTQsImp0aSI6IlpKRnhHUjFPR2p6b2RqWGxoVzJpSzFSeks5VVNwdXE0IiwiaXNzIjpudWxsLCJleHAiOjE3NDEwODc1NTMsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.orS-RbJkYY2nT6r7WKDfL2Wy2M0rJ9Gh_RpZv5kvVvU' ACCEPT = "application/json" HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT} diff --git a/elastic_helper.py b/elastic_helper.py index 4318ff5..95ccc62 100644 --- a/elastic_helper.py +++ b/elastic_helper.py @@ -2,7 +2,6 @@ import zipfile import sys import os import json -from copy import deepcopy from time import sleep from elasticsearch import Elasticsearch,helpers @@ -93,7 +92,6 @@ class ElasticHelper(): for item in s_res['hits']['hits']: if fields : - #item2 = deepcopy(item) item2={} item2['id']=item['_id'] for kf in fields : @@ -153,7 +151,6 @@ class ElasticHelper(): out_json = [] for item in s_res['hits']['hits']: if fields : - #item2 = deepcopy(item) item2={} item2['id']=item['_id'] for kf in fields : @@ -232,8 +229,6 @@ class ElasticHelper(): print( '----', index_name_o, ' complated') - - def deleteIndex(self, index_name) : if not self.es.indices.exists(index=index_name) : print(' ' * 10, " for delete NOT exist index :", index_name ) @@ -376,8 +371,7 @@ class ElasticHelper(): } ] helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) - - + def fileToElastic(self, file_path, index_name, limit_pack = -1): if not os.path.exists(file_path): @@ -454,10 +448,7 @@ class ElasticHelper(): # yield from (hit for hit in data) #return data yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data) - - - - + def es_iterate_all_documents(self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs): """ @@ -571,3 +562,60 @@ class ElasticHelper(): print(e) # save_error(id, e) + + def mappingIndex(self, index_name_i): + # فقط از طریق کیبانا میشه تغییر مپ داد + + # با پایتون نمیشه + # باید ایندکس جدیدی با مپ مطلوب ایجاد کرد و رایندکس کرد + pass + + def updateByQueryIndex(self, index_name_i, body): + ## sample + # body = { + # "script": { + # "inline": "ctx._source.Device='Test'", + # "lang": "painless" + # }, + # "query": { + # "match": { + # "Device": "Boiler" + # } + # } + # } + try: + self.es.update_by_query(body=body, index=index_name_i) + + except Exception as e: + print(e) + # save_error(id, e) + + + def deleteByQueryIndex(self, index_name_i, body): + ## sample + # body = { + # "query": { + # "match": { + # "Device": "Boiler" + # } + # } + # } + try: + self.es.delete_by_query(index=index_name_i, body=body ) + + except Exception as e: + print(e) + # save_error(id, e) + + def delete_by_ids(self, index_name_i, ids): + try: + # ids = ['test1', 'test2', 'test3'] + + query = {"query": {"terms": {"_id": ids}}} + res = self.es.delete_by_query(index=index_name_i, body=query) + print(res) + + except Exception as e: + print(e) + # save_error(id, e) + diff --git a/general_functions.py b/general_functions.py index 0dc71ee..df04088 100644 --- a/general_functions.py +++ b/general_functions.py @@ -2,6 +2,7 @@ from normalizer import Normalizer from tokenizer import * import jalali import re +import sys from re import sub import textwrap from html import escape @@ -968,6 +969,125 @@ def getTitleType(caption: str) -> str: return "اصلی" + +#//////////////////////////////////////////////////////////// +#//////////////////////////////////////////////////////////// + + +# print(os.getcwd()) +def remove_signs(): + str = read_file() + # lines = + pattern = r"\(|\)" + str = re.sub(pattern,'', str) + # str = re.sub(')','', str) + # str = re.sub('/','', str) + + return str + +def read_file(): + with open('./data/DATASET_2.txt', 'r', encoding='utf-8') as file: + text = '' + try: + text = str(file.read()) + except: + pass + return text + +def read_file_by_address(file_address): + with open(file_address, 'a+', encoding='utf-8') as file: + text = '' + try: + # Move the cursor to the beginning of the file to read its content + file.seek(0) + text = file.read() + except: + pass + return text + +def save_to_file(result): + with open('./data/DATASET_3.txt', 'a+', encoding='utf-8') as file: + previous_result = '' + try: + previous_result = file.read() + except: + pass + file.write(result) + file.close() + +def save_to_file_by_address(file_address, text): + with open(file_address, 'a+', encoding='utf-8') as file: + previous_result = '' + try: + previous_result = file.read() + except: + pass + file.write(text) + file.close() + + +# def read_from_excel(file_address, column_name): +# # خواندن فایل اکسل +# data = read_excel(file_address) + +# # استخراج محتوای ستون مورد نظر +# column_data = data[column_name] +# return column_data + +# def add_columndata_to_excel(file_address, column_name, columndata): + +# # خواندن فایل اکسل +# data = read_excel(file_address) + +# # اضافه کردن ستون جدید به داده‌ها +# data[column_name] = columndata + +# # ذخیره کردن داده‌ها در فایل اکسل +# data.to_excel(file_address, index=False) + +def write_to_json(dict, file_address): + + # تبدیل دیکشنری به فرمت JSON + json_data = json.dumps(dict, indent=2, ensure_ascii=False) + + # ذخیره فایل + with open(file_address, 'w+', encoding='utf-8') as file: + file.write(json_data) + + return True + +def read_from_json(file_address): + data_dict = [] + # خواندن اطلاعات از فایل JSON + with open(file_address, 'r', encoding='utf-8') as file: + loaded_data = json.load(file) + + # نمایش اطلاعات خوانده شده + for item in loaded_data: + data_dict.append(item) + return data_dict + + +def separated_date_format_finder(date_ner): + result = False + date_ner = date_ner.replace('.','/') + date_ner = date_ner.replace('،','/') + date_ner = date_ner.replace('ر','/') + #date_pattern = r'\d{1,2} /\d{1,2} /\d{2,4}|\d{1,2}/\d{1,2}/\d{2,4}|\d{2,4} /\d{1,2} /\d{1,2}|\d{2,4}/\d{1,2}/\d{1,2}' + date_pattern = r'\b(?:(?:1[0-2]|0?[1-9])/?(?:3[01]|[12][0-9]|0?[1-9])/?(?:14[0-7][0-9]|13[0-9][0-9]|128[0-9])|(?:1[0-2]|0?[1-9])/?(?:3[01]|[12][0-9]|0?[1-9])/?(?:14[0-7][0-9]|13[0-9][0-9]|128[0-9]|[0-9]{2}))\b' + regex = re.compile(date_pattern) + match_dates = regex.finditer(date_ner) + for date_item in match_dates: + result = True + break + return result + + +#//////////////////////////////////////////////////////////// +#//////////////////////////////////////////////////////////// + + + # prefix, title = normalHeadingTitle("فصل اول - سیاستها و اصول") # print('prefix :', prefix) # print('title :', title) \ No newline at end of file diff --git a/keywords_move.py b/keywords_json_move_to_index.py similarity index 89% rename from keywords_move.py rename to keywords_json_move_to_index.py index 737123a..1d4b464 100644 --- a/keywords_move.py +++ b/keywords_json_move_to_index.py @@ -9,9 +9,9 @@ from elastic_helper import ElasticHelper ## این کد برای استخراج و بهینه سازی کلیدواژه های تولید شده با مدلهای زبانی بزرگ و انتقال به الاستیک نوشته شد ## کلیدواژه ها با ساختار مشخص و مقداری خطا تولید شده بودند -def moveKeywords(elastic, index_name_o, fields=['content'], body={}): +def moveKeywords(elastic, index_name_o, path_file, fields=['content'], body={}): text_normal = TextNormalizer() - dic_main = json.loads(open("data/sections_kw_llama8b_170k_concatenated.json",'r', encoding="utf-8").read()) + dic_main = json.loads(open(path_file,'r', encoding="utf-8").read()) index = 0 percent_prev = 0 list=[] @@ -97,5 +97,7 @@ path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) -#moveKeywords(elastic,"mj_qa_section") +#moveKeywords(elastic,"mj_qa_section", "data/sections_kw_llama8b_170k_concatenated.json") + +moveKeywords(elastic,"mj_qa_section", "data/sections_kw_llama8b_40k_concatenated.json") diff --git a/move_to_other.py b/move_index_to_other.py similarity index 100% rename from move_to_other.py rename to move_index_to_other.py diff --git a/ostan.py b/ostan_to_list.py similarity index 100% rename from ostan.py rename to ostan_to_list.py diff --git a/temp_LawSection_content.py b/temp_LawSection_content.py new file mode 100644 index 0000000..3db415e --- /dev/null +++ b/temp_LawSection_content.py @@ -0,0 +1,180 @@ +import json +import requests +from config_base import * +import pyodbc +import requests +from bs4 import BeautifulSoup +from html import escape +import json +from decimal import Decimal +import datetime +import time +from config_base import * +from general_functions import * +from text_normalizer import TextNormalizer + + +# cursor, cnxn = create_cursor() + +def import_law_section_to_elastic(cursor) : + + query = ''' + select + s.ID as sectionId + ,isnull(s.CAPTION,'') as title -- عنوان بخش: مثلا ماده 5 + ,isnull(s.F_PARENTID,0) as parentId + ,isnull(lss.CAPTION,'') as sectionStatus -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و + ,isnull(lss2.CAPTION,'') as qanon_etebar -- برای کل قانون نه جزء یا ماده خاص : ... منسوخه، معتبر، اصلاحی، موقت و + ,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره + ,isnull(s.SECTIONLEVEL,0) as sectionLevel -- نسبت به عنوان قانون نامرتب و دارای مقدار تکراری هم هست ؟؟؟ + ,isnull(nestedLawType.CAPTION,'') as lawType + --,isnull(nestedLawStatus.CAPTION,'') as lawStatus + ,isnull(s.TEXTORDER,0) as textOrder -- ترتیب نمایش مواد و تبصره ها + ,s.STATENO as stateNo -- ??? + ,isnull(s.SECTIONTYPENO,0) as sectionTypeNumber -- دوهزار رکورد با مقدار صفر دارد اما مقادیر دیگری نیز پذیرفته است ؟؟؟ + -- بیش از پنج هزار رکورد با مقدار بالاتر از 1500 دارد که چنین مقادیری در جدول سکشن_تایپ وجود ندارد پس با این جدول رابطه ندارد + ,isnull(l.CAPTION,'') as lawTitle -- عنوان قانون + ,isnull(l.ID,0) as lawId -- شناسه قانون + ,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب + ,isnull(l.EXPIREDATE,'') as expireDate -- تاریخ انقضا + --,isnull(s.F_LWPHASEID,0) as phaseId -- شناسه فاز + ,s.FULLPATH as sectionFullPath -- عنوان ماده یا تبصره + ,isnull(s.SECTIONTYPENOTEXT,'') as sectionType -- ??? استفساریه، کنوانسیون، موافقت نامه، اساسنامه، تفسیر، دوم ، سوم ، چهارم، دوازدهم، خالی، 1، 2، 3، 4 + ,isnull(s.FIRSTSATENO,0) as firstStateNo -- ??? بازه 0 تا 169 + ,isnull(s.LASTSTATENO,0) as lastStateNo -- ??? بازه 0 تا 112 + ,isnull(s.HIERARCHY,'') as hierarchy + ,isnull(s.DISPLAYINCONTENTS,0) as displayInContents -- ??? صد و پنجاه و سه رکورد دارای مقدار یک و بقیه یک میلیون رکورد مقدار 0 دارد + ,isnull(s.ISINTERPRETATION,0) as isInterpretation -- ??? چهارصد و پنجاه و سه رکورد با مقدار یک دارد و بقیه مقادیر نال است + ,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_TOPICID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM lwsectiontopic where [F_SECTIONID]=s.id) as topics + ,l.[ISLAW] -- قانون + ,l.[ISREGULATION] -- مقرره + ,l.[ISCORRECTIONLETTER] -- اصلاحیه + ,( + SELECT top (1) p3.CAPTION + FROM [lwPhase] p1 + left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID + left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id + where l.ID = p1.F_LWLAWID + order by p2.APPROVEDATE asc + ) as ts_ref -- مرجع تصویب + ,( + SELECT cbt.CAPTION + FROM lwLaw l2 + left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID + where l.ID = l2.id + ) as regulationType + + + from lwSection s + left join lwLawSectionStatus lss on s.F_CMBASETABLEID_SECTIONSTATUS = lss.ID + left join lwLaw l on s.F_LWLAWID = l.ID + left join lwLawSectionStatus lss2 on lss2.id= l.[F_CMBASETABLEID_LASTSTATUS] + left JOIN ( + SELECT l2.F_LWBASETABLEID_LAWTYPE,l2.ID,cbt.CAPTION + FROM lwLaw l2 + left JOIN cmBasetable cbt ON l2.F_LWBASETABLEID_LAWTYPE = cbt.ID + ) AS nestedLawType ON s.F_LWLAWID = nestedLawType.ID + left JOIN ( + SELECT l2.[F_LWBASETABLEID_REGULATIONTYPE],l2.ID,cbt.CAPTION + FROM lwLaw l2 + left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID + ) AS nestedRegulationType ON s.F_LWLAWID = nestedRegulationType.ID + + where l.ISLAW = 1 + order by s.F_LWLAWID,textOrder + ''' + + + cursor.execute(query) + text_normal = TextNormalizer() + + # url = BASE_URL + "repo/majles/section/multi/add" + url = BASE_URL + "repo/majles/section/multi/update" + # dict_topic = json.loads(open("list_LWTopic.json").read()) + + headers = HEADERS + + total_count = 0 + bulk_data = [] + + t1= datetime.datetime.now() + print(t1) + i = 0 + while 1: + # print(i) + i=i+1 + row = cursor.fetchone() + if not row: + break + + # if i > 1000: + # break + # print(row.sectionId) + + html = '' + if isNeedHtml(row.sectionText) : + html = row.sectionText + + try: + soup = BeautifulSoup(row.sectionText, "html.parser") + text = soup.get_text("\n", strip=True) + # text = removeHtmlNoTableTag(row.sectionText) # خطا داره + except Exception as e: + text = row.sectionText + + + text = text_normal.normalize_qanon(text) + content_len = text.__len__() + word_len = len(text_normal.split_words(text)) + + eid='qs'+ str(row.sectionId) + + + data={ + 'id':eid, + 'content': text, + 'content_len': content_len, + 'word_len': word_len + } + + if len(bulk_data) >= 200: + total_count += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid) + payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! + + # limit POST Content-Length 8388608 + pops_data = [] + while len(payload) > 8388608 : + el = bulk_data.pop() + total_count -= 1 + pops_data.append(el) + print(' ' * 10, 'len(payload) ===', str(len(payload)), ' > 8388608 , len(pops_data)='+str(len(pops_data)) ) + payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! + + + response = requests.request("POST", url, headers=headers, data=payload) + if response.status_code != 200 : + print('*' * 10, ' error : len(bulk_data)=', str(len(bulk_data)), ' bulk_data[0]='+ str(bulk_data[0]['id']) , ' bulk_data[-1]='+ str(bulk_data[-1]['id'])) + print(response.text) + bulk_data = pops_data + continue + + bulk_data = pops_data + # print(response) + # print(response.text) + # print(row.txt) + + bulk_data.append(data) + + + + if len(bulk_data) > 0: + total_count += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id']) + payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! + response = requests.request("POST", url, headers=headers, data=payload) + + + print('end success import_law_section_to_elastic') + t2= datetime.datetime.now() + print(t2-t1) diff --git a/temp_codes.py b/temp_codes.py index 2edc3d8..2b42480 100644 --- a/temp_codes.py +++ b/temp_codes.py @@ -7,15 +7,20 @@ from elastic_helper import ElasticHelper from create_relation_tags import * from temp_refactor_gn_dataset import * +from temp_LawSection_content import * + +# cursor, cnxn = create_cursor() +# import_law_section_to_elastic(cursor) + load_dotenv(dotenv_path='config.env') -# host=os.getenv('HOST_160') -# password=os.getenv('HOST_160_PASS') +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_112') +# password=os.getenv('HOST_112_PASS') # host=os.getenv('HOST_60') # password=os.getenv('HOST_60_PASS') @@ -27,19 +32,18 @@ print(host) path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) - - +#------------------------------------------------------- +## +# elastic.backupIndexToZipfile("G:/Project2/111", "gn_dataset") +#moveDataset1(elastic, "G:/Project2/111/gn_dataset_14031125.zip", "gn_dataset2") #------------------------------------------------------- ## -#elastic.backupIndexToZipfile("G:/Project2/111", "gn_dataset") -moveDataset1(elastic, "G:/Project2/111/gn_dataset_14031125.zip", "gn_dataset") - - -## کد نمونه بازیابی از فایل -#path_back = 'G:/Project2/111' -#elastic.restorFileToElastic(path_back, 'gn_dataset_14031125.zip', 'majles', True, 'mj_qa_section') +# ## کد نمونه بازیابی از فایل +# path_back = 'G:/Project2/111/gn_dataset_14031125.zip' +# elastic.createIndex('gn_dataset') +# elastic.zipFileToElastic(path_back, 'gn_dataset') @@ -47,10 +51,6 @@ moveDataset1(elastic, "G:/Project2/111/gn_dataset_14031125.zip", "gn_dataset") #elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section_ai") #elastic.restorFileToElastic("G:/Project2/111", "mj_qa_section_ai", 'majles', True, "mj_qa_section") - - - - #------------------------------------------------------- #### فایده ای نداشت ....!!! ## مسیر درختی مفید تولید نشد و عنوان قانون هم که فیلد مجزا داریم ! @@ -88,6 +88,21 @@ moveDataset1(elastic, "G:/Project2/111/gn_dataset_14031125.zip", "gn_dataset") #------------------------------------------------------- ## +## پشتیبان گیری + +# path_back = os.getcwd() + '/data_back' +#path_back = 'G:/Project2/111' +# if not os.path.exists(path_back) : +# os.makedirs(path_back) +# print('---> path_back = ' + path_back) + +#elastic.backupIndexToZipfile(path_back, "mj_qa_qanon") +# elastic.backupIndexToZipfile(path_back, "mj_qa_section") +# elastic.backupIndexToZipfile(path_back, "mj_qa_section", '', {}, True, [], ["pos_tags", "chunk_tags", "version_info"]) +#elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai") +#elastic.backupIndexToZipfile(path_back, "mj_rg_section") +#elastic.backupIndexToZipfile(path_back, "mj_qa_opinion") + ## کد نمونه بازیابی از فایل # path_back = 'G:/Project2/_back/back_data/data_majles/elastic/v1.0/full' # elastic.restorFileToElastic(path_back, 'mj_qa_section', 'majles') diff --git a/temp_refactor_gn_dataset.py b/temp_refactor_gn_dataset.py index 0858180..bf2e40d 100644 --- a/temp_refactor_gn_dataset.py +++ b/temp_refactor_gn_dataset.py @@ -9,38 +9,94 @@ from elastic_helper import ElasticHelper def moveDataset1(elastic, file, index_name_o): try: try: - list = elastic.iterateJsonFile(file) + list_data = elastic.iterateJsonFile(file) except Exception as e: save_error(0, e) - count = 0 + lst = list(list_data) + index = 0 + percent_prev = 0 text_normal = TextNormalizer() - - for mentry in list: - count += 1 + dict_order={} + for mentry in lst: #print(mentry) + index += 1 + percent = int((index / len(lst)) * 100) + if percent != percent_prev: + print("progress -> %.2f %%" % percent) + percent_prev = percent + + entry = mentry["source"] id = entry.get("id", "") + content = entry.get("content", "") domain = entry.get("domain", "") + order = entry.get("order", "") + time_edit = entry.get("timestamp", "") + user_create = entry.get("user_create", "") + users = entry.get("user_show", []) + result_objects = entry.get("result_objects", []) + meta = entry.get("meta", []) + group_key=domain + ref_info = { + "url" : entry.get("ref_url", ""), + "key" : entry.get("ref_key", ""), + "id" : entry.get("ref_id", "") + } if domain == 'تغییرات قانون': continue + # elif domain == "استخراج کلیدواژه 11 هزارتایی": + # group_key = "پیکره 11 هزارتایی قانون برای کلیدواژه" + elif domain == "AI استخراج کلیدواژه" : + group_key = "پیکره 7 هزار قوانین برای کلیداوژه" + elif domain == "پیکره قوانین 480": + group_key = "پیکره 480 هزار توکن قوانین" + # elif domain == "استخراج کلیدواژه 15 هزارتایی": + # group_key = "پیکره 15 هزار قانون برای کلیدواژه" + #"پیکره آرمان + #"پیکره پیما", + #, + if not order : + if group_key in dict_order : + order = dict_order[group_key]+1 + dict_order[group_key] = order + else: + dict_order[group_key] = 1 + order = 1 + - #"value":"استخراج کلیدواژه 11 هزارتایی" + results = [] + for item in result_objects : + item["user_id"] = user_create + item["time_edit"] = time_edit + results.append(item) - print(id) - #print(entry["content"]) - - # data = {} - # # data["chunk_keywords"]= chunk_keywords - # update = False - # eid = id - # try: - # resp = elastic.update_index_doc(update, index_name_o, eid, data) + #print(id) + + #if len(users) == 0 : + users.append(0) ## یعنی عمومی هست و همه می توانند ببینند + users.append(user_create) + + data = {} + data["id"]= id + data["content"]= content + data["group_key"]= group_key + data["order"]= order + data["ref_info"]= ref_info + data["time_edit"]= time_edit + data["user_create"]= user_create + data["users"]= users + data["meta"]= meta + data["result_objects"]= results + update = False + eid = id + try: + resp = elastic.update_index_doc(update, index_name_o, eid, data) - # except Exception as e: - # save_error(id, e) + except Exception as e: + save_error(id, e) except Exception as e: save_error(id, e) \ No newline at end of file diff --git a/text_normalizer.py b/text_normalizer.py index c37b9a6..e2607d6 100644 --- a/text_normalizer.py +++ b/text_normalizer.py @@ -169,6 +169,14 @@ class TextNormalizer: return text + def date_correction(self, text): + # فرمت YYYY/MM/DD یا YYYY-MM-DD + text = re.sub(r'(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})', '\1/\2/\3', text) + + # فرمت DD/MM/YYYY یا DD-MM-YYYY + text = re.sub(r'(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})', '\3/\2/\1', text) + + def space_correction(self, text): text = re.sub(r"^(بی|می|نمی)( )", r"\1‌", text) diff --git a/parse_tokens.py b/tokens_parse_spell.py similarity index 100% rename from parse_tokens.py rename to tokens_parse_spell.py