llm_codes_import_to_es

This commit is contained in:
hsafaei
2025-09-30 16:40:11 +03:30
parent 8bc0fde102
commit 372251aff7
9 changed files with 402 additions and 170 deletions
+16
View File
@@ -40,6 +40,22 @@ class JSONEncoder(json.JSONEncoder):
return json.JSONEncoder.default(self, obj) return json.JSONEncoder.default(self, obj)
##--------------------------------
# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد
##------------------------------------
def is_section_empty(section_path):
filtered_keys = ['فصل','موخره','امضاء','عنوان']
if '>' in section_path:
path_parts = section_path.split('>')
for key in filtered_keys:
if key in path_parts[-1]:
return True
else:
for key in filtered_keys:
if key in section_path:
return True
return False
def isNeedHtml(html): def isNeedHtml(html):
if "<TABLE" in html or "<table" in html or "</TR" in html or "</tr" in html : if "<TABLE" in html or "<table" in html or "</TR" in html or "</tr" in html :
return True return True
+101 -1
View File
@@ -217,6 +217,105 @@ def moveClassifierAiCodes(elastic, index_name_o, data, version_key = "D51_v1"):
print(f"last ::: send_round -> {len(list_bulk)}") print(f"last ::: send_round -> {len(list_bulk)}")
def moveClassifierAiCodes2( elastic, data_codes, version_key, index_name_i, index_name_o) :
body = {}
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
text_normal = TextNormalizer()
t1= datetime.datetime.now()
print(t1)
send_round = 1
list_bulk=[]
best_code = {}
other_codes = []
eid = 0
try:
for mentry in list:
entry = mentry["source"]
id = entry.get("id", "")
other_info = entry.get("other_info", {})
history_codes = entry.get("history_codes", [])
eid = id
if other_info and is_section_empty(other_info['full_path']) :
continue
if not eid in data_codes :
continue
best_code = data_codes[eid]['best-class']
other_codes = data_codes[eid]['other-classes']
if not best_code and not other_codes :
continue
ai_code = best_code
ai_codes = other_codes
# print(ai_code)
#----------------------------------------------
for label_doc in ai_codes:
label = text_normal.normalize_qanon(label_doc["label"])
label_doc["label"] = label
if label_doc["score"] >= 1 :
label_doc["score"] = label_doc["score"] / 100
history_codes.append({
"version_key": version_key,
"sub_key": "sub",
"label": text_normal.normalize_qanon(label_doc['label']),
"score": label_doc['score'],
})
if ai_code :
if ai_code["score"] >= 1 :
ai_code["score"] = ai_code["score"] / 100
label = ai_code["label"]
label = text_normal.normalize_qanon(ai_code["label"])
ai_code["label"] = label
history_codes.append({
"version_key": version_key,
"sub_key": "main",
"label": text_normal.normalize_qanon(ai_code['label']),
"score": ai_code['score'],
})
#----------------------------------------------
list_bulk.append({
'_id': eid,
'_source': {
"ai_code" : ai_code,
"ai_codes" : ai_codes,
"history_codes": history_codes
}
})
if len(list_bulk) > 200 :
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
# print(f"send_round -> {send_round}")
send_round += 1
except Exception as e:
print("error ---> id ", eid, " message: ", str(e))
if len(list_bulk) :
elastic.updateBulkList(list_bulk, index_name_o)
print(f"last ::: send_round -> {len(list_bulk)}")
load_dotenv(dotenv_path='config.env') load_dotenv(dotenv_path='config.env')
@@ -281,6 +380,7 @@ with open("./data/all_sections_classes_full_140407.json", "r", encoding="utf-8")
classes = json.load(f) classes = json.load(f)
moveClassifierAiCodes(elastic,"mj_qa_section", classes, "D49_v1") # moveClassifierAiCodes(elastic,"mj_qa_section", classes, "D49_v1")
moveClassifierAiCodes2(elastic, classes, "D49_v1","mj_qa_section", "mj_qa_section")
print('finished!') print('finished!')
-16
View File
@@ -15,22 +15,6 @@ from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper from app.common.elastic_helper import ElasticHelper
##--------------------------------
# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد
##------------------------------------
def is_section_empty(section_path):
filtered_keys = ['فصل','موخره','امضاء','عنوان']
if '>' in section_path:
path_parts = section_path.split('>')
for key in filtered_keys:
if key in path_parts[-1]:
return True
else:
for key in filtered_keys:
if key in section_path:
return True
return False
def repair_ai_codes( elastic, index_name_i, index_name_o, file_log) : def repair_ai_codes( elastic, index_name_i, index_name_o, file_log) :
body = {} body = {}
-143
View File
@@ -1,143 +0,0 @@
from pydantic import BaseModel
from typing import List, Optional
import io
import os
import json
import orjson
from collections import defaultdict
from dotenv import load_dotenv
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
import pandas as pd
import json
from pathlib import Path
from openpyxl import Workbook
def excel_to_json(excel_file, required_columns=None, sheet_name=0):
"""
خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری.
Args:
sheet_name: نام sheet (رشته) یا شماره آن (عدد). پیش‌فرض: 0 (اولین sheet)
"""
sheet_names = pd.ExcelFile(excel_file).sheet_names
print("all sheet")
for i, name in enumerate(sheet_names, start=1):
print(f" {i}. {name}")
df = pd.read_excel(excel_file, sheet_name=sheet_name)
if required_columns is None:
selected_columns = df.columns.tolist()
else:
missing = [col for col in required_columns if col not in df.columns]
if missing:
raise ValueError(f"ستون‌های مفقوده در sheet '{sheet_name}': {missing}")
selected_columns = required_columns
return df[selected_columns].to_dict(orient='records')
def update_history_code(data, index_name, elastic=None, sub_key='', qanon_name='' ):
# Base-Model
class DataHistoryIn(BaseModel):
id: str
content: str
path: str
qanon: str
reason: str
confidence: float
class DataHistoryOut(BaseModel):
label: str
score: float
version_key: str = 'llm_cg5m_v1'
sub_key: Optional[List[str]] = ['positve', 'negative']
description: str
version_key= "llm_cg5m_v1"
domain_type = "D51_v1"
text_normalizer = TextNormalizer()
with open("data/ai/domains_list.json", "r", encoding="utf-8") as file:
domains_list = json.load(file)
dict_domain_id = {}
labels_list = []
for item in domains_list[domain_type] :
item["domain_name"] = text_normalizer.normalize_qanon(item["domain_name"])
labels_list.append(item["domain_name"])
dict_domain_id[item["domain_name"]] = str(item["id"])
for i in data :
id = i['id']
res = elastic.get_doctument(index_name, id)
h_data = res['_source']['history_codes']
print(
'='*25,
f'before {type(h_data)} -> {h_data}',
F'id {id}',
sep='\n',
)
new_data = {
"label": text_normalizer.normalize_qanon(qanon_name), # normalize
"score": i['confidence'],
"sub_key": sub_key,
"description": i['reason'],
"version_key": version_key
}
h_data.append(new_data)
for qq in h_data:
if "description" not in qq.keys():
qq['description'] = ''
print(
'='*25,
f'after {type(h_data)} -> {h_data}',
F'id {id}',
sep='\n',
)
try:
resp = elastic.update_index_doc(True, index_name, id, h_data)
except Exception as e:
import traceback
print(traceback.print_exc())
print(f'data NOT saved in es')
break
#######################################################################################################
# exel_path1 = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\insurance_result_score.xlsx"
# qanon_name1 = 'بیمـه‌'
# # p sheet insurance
# # n sheet Non_insurance
# # exel2_path = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\international_trade_result_4.xlsx"
# # p sheet International_Trade
# # n sheet Non_International_Trade
# exel_path3 = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\water_result.xlsx"
# qanon_name3 = 'آب'
# # p sheet water
# # n sheet Non_water
# load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
# path_base_map = "G:/Project2/gateway2_main/repo/_other/"
# elastic = ElasticHelper(host, password, "elastic", path_base_map)
# # positve
# # negative
# result = excel_to_json(excel_file=exel_path1, sheet_name='insurance')
# result_f = update_history_code(data=result,elastic=elastic,index_name='mj_qa_section', sub_key='positve', qanon_name=qanon_name1)
# o1= r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\test1_excel.json'
+276
View File
@@ -0,0 +1,276 @@
# from pydantic import BaseModel
from typing import List, Optional
import io
import os
import json
from collections import defaultdict
from dotenv import load_dotenv
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
import pandas as pd
import json
from pathlib import Path
from openpyxl import Workbook
# # Base-Model
# class DataHistoryIn(BaseModel):
# id: str
# content: str
# path: str
# qanon: str
# reason: str
# confidence: float
# class DataHistoryOut(BaseModel):
# label: str
# score: float
# version_key: str = "llm_cg5m_v1"
# sub_key: Optional[List[str]] = ["positve", "negative"]
# description: str
text_normalizer = TextNormalizer()
def excel_to_json(excel_file, required_columns=None, sheet_name=0):
"""
خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری.
Args:
sheet_name: نام sheet (رشته) یا شماره آن (عدد). پیش‌فرض: 0 (اولین sheet)
"""
sheet_names = pd.ExcelFile(excel_file).sheet_names
print("all sheet")
for i, name in enumerate(sheet_names, start=1):
print(f" {i}. {name}")
df = pd.read_excel(excel_file, sheet_name=sheet_name)
if required_columns is None:
selected_columns = df.columns.tolist()
else:
missing = [col for col in required_columns if col not in df.columns]
if missing:
raise ValueError(f"ستون‌های مفقوده در sheet '{sheet_name}': {missing}")
selected_columns = required_columns
return df[selected_columns].to_dict(orient="records")
def update_history_code(elastic, data, index_name_o, sub_key, label_name, version_key):
send_round = 1
index = 1
list_bulk=[]
total = len(data)
percent = 0
eid = 0
try:
for item in data:
id = item["id"]
index += 1
# if id in ["qs1002289", "qs1002290"] :
# continue
eid = id
res = elastic.get_doctument(index_name_o, eid)
history_codes = res["_source"]["history_codes"]
new_data = {
"label": text_normalizer.normalize_qanon(label_name), # normalize
"sub_key": sub_key,
"description": item["reason"],
"version_key": version_key,
}
if "confidence" in item:
new_data["score"] = item["confidence"]
history_codes.append(new_data)
# for qq in h_data:
# if "description" not in qq.keys():
# qq['description'] = ''
list_bulk.append(
{
"_id": eid,
"_source": {
"history_codes": history_codes,
},
}
)
if len(list_bulk) > 200:
_percent = int ( (index * 100) / total)
print(f" --> {_percent}% index {index}/{total} id {eid}", sep="\n")
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
# print(f"send_round -> {send_round}")
send_round += 1
except Exception as e:
print("error ---> id ", eid, " message: ", str(e))
if len(list_bulk):
elastic.updateBulkList(list_bulk, index_name_o)
print(f"last ::: send_round -> {len(list_bulk)}")
def run_all_excels_codes(elastic, excel_path_base, list_excel, version_key ):
for item in list_excel :
result = excel_to_json(excel_path_base + item["file"], sheet_name=0)
print( "########## positve ########### ended file to json ", len(result) , item["label"] )
update_history_code( elastic, result, "mj_qa_section", "positve", item["label"], version_key)
result = excel_to_json(excel_path_base + item["file"], sheet_name=1)
print( "########## negative ########### ended file to json ", len(result) , item["label"] )
update_history_code( elastic, result, "mj_qa_section", "negative", item["label"], version_key)
def run_all_json_codes(elastic, path_base, index_name_o, version_key):
path = Path(path_base)
# به‌دست آوردن لیست فایل‌های JSON
json_files = list(path.glob('*.json'))
# jump = True
# jump_id = True
for file in json_files :
file_path = Path(file)
label_name = file_path.stem.replace("_batch_result", "").strip()
if "log" in label_name :
print( " !!!!!!!-------jumped---------> is log ... ", file_path.stem)
continue
label_name = text_normalizer.normalize_qanon(label_name)
###--- بخاطر خطای خاص در اجرای اول و نیاز به پرش در ادامه
# if label_name == "نظام‌های صنفی و حرفه‌ای" :
# jump = False
# jump_id = True
# if jump :
# print( "jump ", label_name )
# continue
if label_name in ["تجارت خارجی", "آب", "بیمه"] :
print( " !!!!!!!----------------> duplicate by excel ... ", label_name)
continue
data = {}
with open(file, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
send_round = 1
index = 1
list_bulk=[]
total = len(data.items())
eid = 0
try:
print( "########## start ########### json to es ", total , label_name )
for id, item in data.items() :
index += 1
eid = id
# if id == "qs876345" :
# jump_id = False
# if jump_id :
# print( "jump_id ", eid )
# continue
if "error" in item :
continue
if not "rel" in item :
continue
res = elastic.get_doctument(index_name_o, eid)
history_codes = res["_source"]["history_codes"]
sub_key = "positive"
if not item["rel"] :
sub_key = "negative"
new_data = {
"label": label_name,
"sub_key": sub_key,
"description": item["reason"],
"version_key": version_key,
}
if "confidence" in item:
new_data["score"] = item["confidence"]
history_codes.append(new_data)
list_bulk.append(
{
"_id": eid,
"_source": {
"history_codes": history_codes,
},
}
)
if len(list_bulk) > 200:
_percent = int ( (index * 100) / total)
print(f" --> {_percent}% index {index}/{total} id {eid}", sep="\n")
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
# print(f"send_round -> {send_round}")
send_round += 1
except Exception as e:
print("error ---> id ", eid, " message: ", str(e))
if len(list_bulk):
elastic.updateBulkList(list_bulk, index_name_o)
print(f"last ::: send_round -> {len(list_bulk)}")
#######################################################################################################
load_dotenv(dotenv_path='config.env')
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#----------------------------------------------------------------
#------یکبار اجرا شد و نباید تکرار شود
excel_path_base = "data/ai/llm_codes/"
list_excel = [
# {
# "file" : "insurance_result_score.xlsx",
# "label" : "بیمه"
# },
# {
# "file" : "international_trade_result_4.xlsx",
# "label" : "تجارت خارجی"
# },
# {
# "file" : "water_result.xlsx",
# "label" : "آب"
# }
]
# run_all_excels_codes(elastic, excel_path_base, list_excel, "llm_cg5m_v1")
#----------------------------------------------------------------
#------یکبار اجرا شد و نباید تکرار شود
# path_base = "data/ai/llm_codes/batch_entity_result/"
# run_all_json_codes(elastic, path_base, "mj_qa_section", "llm_cg5m_v1")
#----------------------------------------------------------------
+9 -10
View File
@@ -11,8 +11,8 @@ from app.temp_refactor_gn_dataset import *
load_dotenv(dotenv_path="config.env") load_dotenv(dotenv_path="config.env")
# host = os.getenv("HOST_160") host = os.getenv("HOST_160")
# password = os.getenv("HOST_160_PASS") password = os.getenv("HOST_160_PASS")
# host=os.getenv('HOST_112') # host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS') # password=os.getenv('HOST_112_PASS')
@@ -23,8 +23,8 @@ load_dotenv(dotenv_path="config.env")
# host=os.getenv('HOST_118') # host=os.getenv('HOST_118')
# password=os.getenv('HOST_118_PASS') # password=os.getenv('HOST_118_PASS')
host=os.getenv('HOST_60') # host=os.getenv('HOST_60')
password=os.getenv('HOST_60_PASS') # password=os.getenv('HOST_60_PASS')
# host=os.getenv('HOST_161') # host=os.getenv('HOST_161')
# password=os.getenv('HOST_161_PASS') # password=os.getenv('HOST_161_PASS')
@@ -42,12 +42,14 @@ print(host)
path_base_map = "G:/Project2/gateway2_main/repo/_other/" path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map) elastic = ElasticHelper(host, password, "elastic", path_base_map)
# elastic.backupIndexToZipfile("G:/Project2/111/haditha", "dh_volume") # elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
# elastic.backupIndexToZipfile("G:/Project2/111/haditha", "dh_haditha") # elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting')
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_spr_sanad") # elastic.backupIndexToZipfile("G:/Project2/111", "mn_spr_sanad")
# elastic.createIndex( 'mn_spr_sanad', 'monir', 'mn_spr_sanad') # elastic.createIndex( 'mn_spr_sanad', 'monir', 'mn_spr_sanad')
elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', 'monir', False, 'mn_spr_sanad') # elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', 'monir', False, 'mn_spr_sanad')
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_domain") # elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_domain")
# elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_domain') # elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_domain')
@@ -70,9 +72,6 @@ elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad',
# elastic.restorFileToElastic2('G:/Project2/111/mn_sanad.zip', 'mn_sanad', 'monir', False, 'mn_sanad') # elastic.restorFileToElastic2('G:/Project2/111/mn_sanad.zip', 'mn_sanad', 'monir', False, 'mn_sanad')
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting')
# ------------------------------------------------------- # -------------------------------------------------------
## ##
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha") # elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")