Compare commits

..
10 Commits
Author SHA1 Message Date
init_mahdi 69d8af4b18 first commit 2026-11-23 20:06:18 +03:30
init_mahdi 179d37336b first commit 2026-11-23 20:05:13 +03:30
hsafaei 13253bf2df 1 2026-07-15 19:29:16 +03:30
hsafaei cd3c93c7ae 1 2026-07-04 14:35:30 +03:30
hsafaei ed1e7fe6b6 async , not conflict 2026-07-04 11:50:14 +03:30
hsafaei cd174a33c0 Merge branch 'master' of http://192.168.23.150:3000/develop/dataParsers 2026-07-02 14:26:48 +03:30
hsafaei 8e2bc114f1 1 2026-07-02 14:26:46 +03:30
sisrsis a578a26e07 write async update bulk 2026-07-02 14:09:12 +03:30
sisrsis 63a2193b07 fix bug time out 2026-07-02 11:30:17 +03:30
hsafaei 52dab527a5 1 2026-07-02 10:53:04 +03:30
25 changed files with 4776 additions and 1616 deletions
+6
View File
@@ -51,3 +51,9 @@ mj_qa_section.json
rerank_data.json rerank_data.json
test1.json test1.json
schema/mj_qa_conflict.json schema/mj_qa_conflict.json
mn_meet_for_section.json
qs_data_for_h100_1.json
test.json
app/mapping/majles_mj_qa_rule_embeding.json
app/mapping/monir_mn_voice_sanad.json
app/monir/p1_changed_id_item.json
+288 -27
View File
@@ -4,6 +4,8 @@ import os
import json import json
from time import sleep from time import sleep
from elasticsearch import Elasticsearch, helpers from elasticsearch import Elasticsearch, helpers
from pathlib import Path
import orjson
class ElasticHelper: class ElasticHelper:
@@ -91,7 +93,6 @@ class ElasticHelper:
res = self.es.exists(index=index_name, id=id) res = self.es.exists(index=index_name, id=id)
return res return res
def update_index_doc(self, is_update_state, index_name_o, eid, data): def update_index_doc(self, is_update_state, index_name_o, eid, data):
""" """
نوع ورودی: نوع ورودی:
@@ -103,7 +104,7 @@ class ElasticHelper:
عملیات: عملیات:
- اگر is_update_state=True باشد: سند را آپدیت می‌کند - اگر is_update_state=True باشد: سند را آپدیت می‌کند
- در غیر این صورت: سند جدید ایجاد می‌کند - در غیر این صورت: سند جدید ایجاد می‌کند
""" """
if is_update_state: if is_update_state:
resp = self.es.update(index=index_name_o, id=eid, doc=data) resp = self.es.update(index=index_name_o, id=eid, doc=data)
# resp = self.es.update(index=index_name_o, id=eid, body={'doc':data}) # resp = self.es.update(index=index_name_o, id=eid, body={'doc':data})
@@ -135,6 +136,7 @@ class ElasticHelper:
fields=[], fields=[],
mode="normal", mode="normal",
collapse_field="", collapse_field="",
size=1000,
): ):
print("*" * 50, " start backup -->", index_name) print("*" * 50, " start backup -->", index_name)
self.counter = 0 self.counter = 0
@@ -144,7 +146,7 @@ class ElasticHelper:
if out_name == "": if out_name == "":
out = index_name out = index_name
s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body) s_res = self.es.search(index=index_name, scroll="5m", size=size, body=body)
self.total = s_res["hits"]["total"]["value"] self.total = s_res["hits"]["total"]["value"]
print("start index = %s" % index_name) print("start index = %s" % index_name)
@@ -270,7 +272,7 @@ class ElasticHelper:
if body == {}: if body == {}:
s_res = self.es.search(index=index_name, scroll="5m", size=1000) s_res = self.es.search(index=index_name, scroll="5m", size=1000)
else: else:
if not "size" in body : if not "size" in body:
body["size"] = 1000 body["size"] = 1000
s_res = self.es.search(index=index_name, scroll="5m", body=body) s_res = self.es.search(index=index_name, scroll="5m", body=body)
self.total = s_res["hits"]["total"]["value"] self.total = s_res["hits"]["total"]["value"]
@@ -349,7 +351,13 @@ class ElasticHelper:
# - داده‌ها را از فایل ZIP به Elasticsearch بازیابی می‌کند # - داده‌ها را از فایل ZIP به Elasticsearch بازیابی می‌کند
# -----------------------------end---------------------------- # -----------------------------end----------------------------
def restorFileToElastic( def restorFileToElastic(
self, path_back, index_name, app_key="", queryDelete=True, map_name="", mapping_file_path = "" self,
path_back,
index_name,
app_key="",
queryDelete=True,
map_name="",
mapping_file_path="",
): ):
if not os.path.exists(path_back): if not os.path.exists(path_back):
print(" **** error *** path not exist: ", path_back) print(" **** error *** path not exist: ", path_back)
@@ -369,7 +377,13 @@ class ElasticHelper:
self.zipFileToElastic(file_path, index_name) self.zipFileToElastic(file_path, index_name)
def restorFileToElastic2( def restorFileToElastic2(
self, path_file, index_name, app_key="", queryDelete=True, map_name="", mapping_file_path = "" self,
path_file,
index_name,
app_key="",
queryDelete=True,
map_name="",
mapping_file_path="",
): ):
if not os.path.exists(path_file): if not os.path.exists(path_file):
print(" **** error *** path not exist: ", path_file) print(" **** error *** path not exist: ", path_file)
@@ -526,9 +540,9 @@ class ElasticHelper:
# - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند # - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند
# - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود # - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود
# -----------------------------end---------------------------- # -----------------------------end----------------------------
def createIndex(self, index_name, app_key="", map_name="", mapping_file_path = ""): def createIndex(self, index_name, app_key="", map_name="", mapping_file_path=""):
if not mapping_file_path : if not mapping_file_path:
path_base = self.path_mappings path_base = self.path_mappings
path_mapping1 = path_base + "general/" path_mapping1 = path_base + "general/"
if app_key == "": if app_key == "":
@@ -598,8 +612,8 @@ class ElasticHelper:
"doc": item["_source"], "doc": item["_source"],
} }
) )
if streem_state : if streem_state:
### /// برای مواردی که نیاز هست خطا فهمیده شود ### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk( for ok, result in helpers.streaming_bulk(
self.es, self.es,
@@ -608,9 +622,9 @@ class ElasticHelper:
raise_on_exception=False, raise_on_exception=False,
): ):
if not ok: if not ok:
print("Error:", result) print("Error:", result)
else : else:
helpers.bulk( helpers.bulk(
self.es, self.es,
actions, actions,
@@ -638,7 +652,7 @@ class ElasticHelper:
stats_only = True stats_only = True
yield_ok = False yield_ok = False
actions=[] actions = []
for item in listData: for item in listData:
actions.append( actions.append(
{ {
@@ -648,8 +662,8 @@ class ElasticHelper:
"_source": item["_source"], "_source": item["_source"],
} }
) )
if streem_state : if streem_state:
### /// برای مواردی که نیاز هست خطا فهمیده شود ### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk( for ok, result in helpers.streaming_bulk(
self.es, self.es,
@@ -658,9 +672,9 @@ class ElasticHelper:
raise_on_exception=False, raise_on_exception=False,
): ):
if not ok: if not ok:
print("Error:", result) print("Error:", result)
else : else:
helpers.bulk( helpers.bulk(
self.es, self.es,
actions, actions,
@@ -681,7 +695,9 @@ class ElasticHelper:
# - داده‌ها را به صورت bulk وارد می‌کند # - داده‌ها را به صورت bulk وارد می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند # - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end---------------------------- # -----------------------------end----------------------------
def importJsonDataToElastic(self, jsonData, index_name, fields=[], streem_state = False): def importJsonDataToElastic(
self, jsonData, index_name, fields=[], streem_state=False
):
chunk_size = 100000 chunk_size = 100000
raise_on_error = False raise_on_error = False
raise_on_exception = False raise_on_exception = False
@@ -707,7 +723,7 @@ class ElasticHelper:
"_source": source, "_source": source,
} }
) )
if streem_state : if streem_state:
### /// برای مواردی که نیاز هست خطا فهمیده شود ### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk( for ok, result in helpers.streaming_bulk(
self.es, self.es,
@@ -716,9 +732,9 @@ class ElasticHelper:
raise_on_exception=False, raise_on_exception=False,
): ):
if not ok: if not ok:
print("Error:", result) print("Error:", result)
else : else:
success, errors = helpers.bulk( success, errors = helpers.bulk(
self.es, self.es,
actions, actions,
@@ -729,7 +745,6 @@ class ElasticHelper:
yield_ok, yield_ok,
) )
return success, errors return success, errors
# ----------------------------start--------------------------- # ----------------------------start---------------------------
# متد fileToElastic: # متد fileToElastic:
@@ -899,7 +914,7 @@ class ElasticHelper:
scroll=scroll_timeout, scroll=scroll_timeout,
**kwargs, **kwargs,
size=pagesize, size=pagesize,
body=body body=body,
) )
else: else:
result = self.es.search( result = self.es.search(
@@ -1176,3 +1191,249 @@ class ElasticHelper:
except Exception as e: except Exception as e:
print(e) print(e)
# save_error(id, e) # save_error(id, e)
def save_orjson(self, path, data):
"""
تابع برای ذخیره لیست و جیسون با سرعت بالا
:param path: آدرس خروجی با پسوند json
:param data: داده خروجی برای ذخیره
"""
with open(path, "wb") as f:
f.write(
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
)
def load_orjson(self, path: str | Path):
"""
تابع برای بارگزاری جیسون با نهایت سرعت
path: آدرس کامل فایل ورودی
"""
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
def backup_entire_index(
self,
index_name: str,
output_dir: str | Path,
batch_size: int = 1000,
):
"""Backup کامل Elasticsearch index.
شامل:
- _index
- _id
- _score
- _routing
- _version
- _seq_no
- _primary_term
- کل _source
- تمام dense_vector ها
- سایر fields
نکته:
dense_vector هایی که به دلیل
index.mapping.exclude_source_vectors
از _source حذف شده‌اند نیز از طریق fields
بازیابی می‌شوند.
Parameters
----------
es:
Elasticsearch client
index_name:
نام index
output_dir:
مسیر فایل JSON خروجی
batch_size:
تعداد document در هر batch
"""
output_dir = Path(output_dir)
output_dir.parent.mkdir(
parents=True,
exist_ok=True,
)
def find_vector_fields(
properties,
prefix="",
):
if not properties:
return
for field_name, field_mapping in properties.items():
full_name = f"{prefix}.{field_name}" if prefix else field_name
if field_mapping.get("type") == "dense_vector":
vector_fields.append(full_name)
nested_properties = field_mapping.get("properties")
if nested_properties:
find_vector_fields(
nested_properties,
full_name,
)
print("=" * 70)
print(f"BACKUP START")
print(f"Index : {index_name}")
print(f"Output : {output_dir}")
print("=" * 70)
total = self.es.count(index=index_name)["count"] # تعداد کل documentها
print(f"Total documents: {total:,}")
if total == 0:
print("Index is empty.")
return
################### پیدا کردن تمام dense_vector ها از mapping
mapping_response = self.es.indices.get_mapping(index=index_name)
mapping = mapping_response[index_name]["mappings"]
vector_fields = []
find_vector_fields(mapping.get("properties", {}))
print()
if vector_fields:
print("Dense vector fields:")
for field in vector_fields:
print(f" - {field}")
else:
print("Dense vector fields: None")
search_kwargs = {
"index": index_name,
"size": 1000,
"query": {"match_all": {}},
"sort": [{"_shard_doc": "asc"}],
}
if vector_fields:
search_kwargs["fields"] = vector_fields
######################## Backup
documents = []
counter = 1
processed = 0
search_after = None
while True:
if search_after is not None:
search_kwargs["search_after"] = search_after
response = self.es.search(**search_kwargs)
hits = response["hits"]["hits"]
if not hits:
break
for hit in hits:
document = {}
for key in (
"_index",
"_id",
"_score",
"_routing",
"_version",
"_seq_no",
"_primary_term",
):
if key in hit:
document[key] = hit[key]
source = hit.get(
"_source",
{},
)
if source is None:
source = {}
else:
source = dict(source)
fields = hit.get(
"fields",
{},
)
for vector_field in vector_fields:
vector = fields.get(vector_field)
if vector is None:
continue
if (
isinstance(vector, list)
and len(vector) == 1
and isinstance(vector[0], list)
):
vector = vector[0]
parts = vector_field.split(".")
target = source
for part in parts[:-1]:
if not isinstance(
target.get(part),
dict,
):
target[part] = {}
target = target[part]
target[parts[-1]] = vector
document["_source"] = source
other_fields = {
key: value
for key, value in fields.items()
if key not in vector_fields
}
if other_fields:
document["fields"] = other_fields
documents.append(document)
processed += 1
if len(documents) >= batch_size:
percent = processed / total * 100
print(
f"\rProgress: " f"{processed:,}/{total:,} " f"({percent:.2f}%)",
end="",
flush=True,
)
self.save_orjson(
path=output_dir / f"part_{counter}.json",
data=documents,
)
documents = []
counter += 1
search_after = hits[-1]["sort"]
print()
if len(documents) > 0:
self.save_orjson(
path=output_dir / f"part_{counter}.json",
data=documents,
)
print()
print("=" * 70)
print("BACKUP FINISHED")
print(f"Documents : {processed:,}")
print(f"Output : {output_dir}")
print("=" * 70)
if processed != total:
print(
f"WARNING: "
f"expected {total:,} documents, "
f"but backed up {processed:,}."
)
else:
print("Document count: OK")
return {
"index": index_name,
"total": total,
"backed_up": processed,
"output": str(output_dir),
"vector_fields": vector_fields,
}
+126 -378
View File
@@ -1,400 +1,148 @@
from elasticsearch import AsyncElasticsearch import zipfile
from elasticsearch.helpers import async_bulk
import sys import sys
import os import os
import asyncio
import aiofiles
import json import json
from dotenv import load_dotenv
from zipfile import ZipFile
from time import sleep from time import sleep
import gc from elasticsearch import AsyncElasticsearch, helpers
from elasticsearch.helpers import async_bulk ,BulkIndexError
class ElasticHelperAsync:
"""
کلاس ElasticHelper:
نوع ورودی: بدون ورودی مستقیم در تعریف کلاس
نوع خروجی: شیء از نوع ElasticHelper
عملیات:
- متغیرهای کلاسی برای شمارش و مدیریت عملیات تعریف می‌کند
- مسیر پیش‌فرض مپینگ‌ها را تنظیم می‌کند
"""
class elastic_helper_async: counter = 0
total = 0
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mapping = ""): id = ""
path_mappings = os.getcwd() + "/repo/_other/"
# self.limit_data = os.getenv("ELASTIC_LIMIT_IMPORT") def __init__(
# self.app_key = os.getenv("APP_KEY") self,
es_url="http://127.0.0.1:6900",
es_pass="",
es_user="elastic",
path_mappings="",
):
"""
نوع ورودی:
- es_url: آدرس Elasticsearch (str) - پیش‌فرض "http://127.0.0.1:6900"
- es_pass: رمز عبور (str) - پیش‌فرض خالی
- es_user: نام کاربری (str) - پیش‌فرض "elastic"
- path_mappings: مسیر مپینگ‌ها (str) - پیش‌فرض خالی
نوع خروجی: شیء ElasticHelper
عملیات:
- اتصال به Elasticsearch را برقرار می‌کند
- در صورت وجود رمز عبور، از احراز هویت استفاده می‌کند
- تا 10 بار برای اتصال مجدد تلاش می‌کند (هر بار 5 ثانیه انتظار)
- در صورت عدم موفقیت، پیام خطا نمایش داده می‌شود
"""
if path_mappings:
self.path_mappings = path_mappings
if path_mapping : if es_pass == "":
self.path_mapping = path_mapping self.es = AsyncElasticsearch(es_url,request_timeout=500)
if es_pass == '' :
self.aes = AsyncElasticsearch(es_url, timeout=100000000)
else: else:
self.aes = AsyncElasticsearch(es_url, basic_auth=(es_user, es_pass),timeout=100000000) self.es = AsyncElasticsearch(
es_url,
print(es_url) http_auth=(es_user, es_pass),request_timeout=500
print(self.aes) )
self.success_connect = False
for a in range(0,10):
try :
if not self.es.ping():
print('elastic not ping, sleep 30 s : ', a)
sleep(5)
continue
else:
self.success_connect = True
break
except Exception as e:
break
if not self.success_connect :
print('******','not access to elastic service')
return
# print(es_url)
# print(self.es)
# self.success_connect = False
# for a in range(0, 10):
# try:
# if not self.es.ping():
# print("elastic not ping, sleep 30 s : ", a)
# sleep(5)
# continue
# else:
# self.success_connect = True
# break
# except Exception as e:
# break
# if not self.success_connect:
# print("******", "not access to elastic service")
# return
self.success_connect = True
self.counter = 0 self.counter = 0
self.total = 0 self.total = 0
self.id = "" self.id = ""
async def test_file(self,array: list, name_s): async def get_document(self, index_name, id):
for a in array: res = await self.es.get(index=index_name, id=id)
if a == name_s: return res
return True
return False
async def name_file(self,array: list, namber_claer:str): # ----------------------------start---------------------------
data = [] # متد importBulkList:
for a in array: # نوع ورودی:
data.append(a[:-namber_claer]) # - listData: لیست داده‌ها (list)
# - index_name: نام اندیس (str)
print(data) # نوع خروجی: بدون خروجی مستقیم
return data # عملیات:
# - داده‌ها را به صورت bulk وارد می‌کند
async def read_file_json_mapping(self, name_map_general ): # - از helpers.bulk Elasticsearch استفاده می‌کند
async with aiofiles.open(f"{self.path_mapping}/general/" + name_map_general + ".json", mode="r", encoding="utf8") as file_json: # -----------------------------end----------------------------
data_mapping_josn = await file_json.read() async def data_pars_import(self, listData, index_name):
data_mapping_josn = json.loads(data_mapping_josn) for item in listData:
return data_mapping_josn yield(
{
"_op_type": "index",
async def create_general_indexes(self): "_index": index_name,
mapping_general = f"{self.path_mapping}/general/" "_id": item["_id"],
list_general=['gn_setting','gn_calendar' ,'gn_dataset','gn_entity','gn_log_action','gn_log_change','gn_log_search','gn_research' ] "_source": item["_source"],
}
for seed_general in list_general: )
print("mapping "+seed_general)
data_json_mapping = await self.read_file_json_mapping(seed_general) async def data_pars_update(self, listData, index_name):
try: for item in listData:
await self.aes.indices.create(index=seed_general, body=data_json_mapping) yield(
except: {
print("This file has already been created, and I cannot create it again.") "_op_type": "update",
"_index": index_name,
"_id": item["_id"],
async def create_mapping_delete(self,location_file_zip:str, app_key="majles"): "doc": item["_source"],
locations_data_ok = [] }
location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/") )
location_mapping_general = os.listdir(f"{self.path_mapping}/general/") async def importBulkList(self, listData, index_name):
location_filezip = os.listdir(location_file_zip) try:
name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5) await async_bulk(
name_locations_mapping_general = await self.name_file(location_mapping_general, 5) client=self.es,
name_locations_filezip = await self.name_file(location_filezip, 4) actions=self.data_pars_import(listData, index_name),
raise_on_error=True,
for a in name_locations_filezip: raise_on_exception=True,
if await self.test_file(name_locations_mapping_majles, a): )
print(a) except BulkIndexError as e:
async with aiofiles.open(f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8") as file_json: for err in e.errors:
data_mapping_josn = await file_json.read() print(err)
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif await self.test_file(name_locations_mapping_general, a):
print(a)
async with aiofiles.open(
f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
if a == "mj_rg_section" or a == "semantic_search":
mapping_read = "mj_qa_section"
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif a[-3:] == "_ai":
mapping_read = a[:-3]
try:
async with aiofiles.open(
f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
except:
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
print(f"not funds map {a}")
return locations_data_ok
## error for to for
async def create_mapping(self,location_file_zip:str, app_key="majles"):
locations_data_ok = []
location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/")
location_mapping_general = os.listdir(f"{self.path_mapping}/general/")
location_filezip = os.listdir(location_file_zip)
name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5)
name_locations_mapping_general = await self.name_file(location_mapping_general, 5)
name_locations_filezip = await self.name_file(location_filezip, 4)
for a in name_locations_filezip:
if await self.test_file(name_locations_mapping_majles, a):
print(a)
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif await self.test_file(name_locations_mapping_general, a):
print(a)
async with aiofiles.open(
f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
if a == "mj_rg_section" or a == "semantic_search":
mapping_read = "mj_qa_section"
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif a[-3:] == "_ai":
mapping_read = a[:-3]
try:
async with aiofiles.open(
f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
except:
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
print(f"not funds map {a}")
return locations_data_ok
## error for to for
async def data_unzip(self,location_file_zip:str,namefile: str):
current_directory = os.getcwd()
file_name = f"{location_file_zip}/{namefile}.zip"
sleep(10)
print(" -----> start to unzip ... ",file_name)
data1 = []
os.system(f"del /q /S .\\data\\tmp\\edb\\{namefile}")
os.system(f"mkdir .\\data\\tmp\\edb\\{namefile}")
# os.system(f"del -rf /q .\\data\\tmp\\edb\\{namefile}\\*")
os.system(f"tar -xf {file_name} -C .\\data\\tmp\\edb\\{namefile}\\")
#await asyncio.sleep(1)
list_file_json = os.listdir(f".\\data\\tmp\\edb\\{namefile}\\")
await asyncio.sleep(10)
for a in list_file_json:
try:
with open(f"{current_directory}\\data\\tmp\\edb\\{namefile}\\{a}", "r", encoding="utf8") as file_json:
data = file_json.read()
data = json.loads(data)
for a1 in data:
#await asyncio.sleep(0.001)
try:
yield (
{
"_op_type": "index",
"_index": namefile,
"_id": a1["_id"],
"_source": a1["_source"],
}
)
except:
print("error type document")
except Exception as e:
print(f"read file {current_directory}\\data\\tmp\\edb\\{namefile}\\{a}" + " " + {e})
async def go_to_data(list_data: list, namefile: str):
with open(f"T:{namefile}.json", "a") as a:
a.write(str(list_data))
a.close()
async def run_elastic_import(self,loc:str):
locations_data = await self.create_mapping(loc)
print(locations_data)
await self.create_general_indexes()
#await asyncio.sleep(5)
for file_list in locations_data:
# try :
await async_bulk(self.aes, self.data_unzip(loc,file_list), True)
gc.collect()
# except:
# await asyncio.sleep(10)
# await async_bulk(self.aes, self.data_unzip(file_list), True)
print("finash")
#await asyncio.sleep(10)
async def run_elastic_import_delete(self,loc:str):
locations_data = await self.create_mapping_delete(loc)
#await asyncio.sleep(1000)
print(locations_data)
await self.create_general_indexes()
#await asyncio.sleep(5)
for file_list in locations_data:
# try :
await async_bulk(self.aes, self.data_unzip(loc,file_list), True)
gc.collect()
# except:
# await asyncio.sleep(10)
# await async_bulk(self.aes, self.data_unzip(file_list), True)
print("finash")
#await asyncio.sleep(10)
async def delete_index(self,name_index:str):
await self.aes.indices.delete(index=name_index, ignore=[400, 404]) # await go_to_data( data2,"gn_dataset")
async def updateBulkList(self, listData, index_name, streem_state=False):
chunk_size = 100000
raise_on_error = False
raise_on_exception = False
stats_only = True
yield_ok = False
try:
await async_bulk(
client=self.es,
actions=self.data_pars_update(listData, index_name),
raise_on_error=raise_on_error,
raise_on_exception=raise_on_exception,
yield_ok=yield_ok,
chunk_size = chunk_size,
stats_only=stats_only
)
except BulkIndexError as e:
for err in e.errors:
print(err)
@@ -0,0 +1,400 @@
from elasticsearch import AsyncElasticsearch
from elasticsearch.helpers import async_bulk
import sys
import os
import asyncio
import aiofiles
import json
from dotenv import load_dotenv
from zipfile import ZipFile
from time import sleep
import gc
class elastic_helper_async:
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mapping = ""):
# self.limit_data = os.getenv("ELASTIC_LIMIT_IMPORT")
# self.app_key = os.getenv("APP_KEY")
if path_mapping :
self.path_mapping = path_mapping
if es_pass == '' :
self.aes = AsyncElasticsearch(es_url, timeout=100000000)
else:
self.aes = AsyncElasticsearch(es_url, basic_auth=(es_user, es_pass),timeout=100000000)
print(es_url)
print(self.aes)
self.success_connect = False
for a in range(0,10):
try :
if not self.es.ping():
print('elastic not ping, sleep 30 s : ', a)
sleep(5)
continue
else:
self.success_connect = True
break
except Exception as e:
break
if not self.success_connect :
print('******','not access to elastic service')
return
self.counter = 0
self.total = 0
self.id = ""
async def test_file(self,array: list, name_s):
for a in array:
if a == name_s:
return True
return False
async def name_file(self,array: list, namber_claer:str):
data = []
for a in array:
data.append(a[:-namber_claer])
print(data)
return data
async def read_file_json_mapping(self, name_map_general ):
async with aiofiles.open(f"{self.path_mapping}/general/" + name_map_general + ".json", mode="r", encoding="utf8") as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
return data_mapping_josn
async def create_general_indexes(self):
mapping_general = f"{self.path_mapping}/general/"
list_general=['gn_setting','gn_calendar' ,'gn_dataset','gn_entity','gn_log_action','gn_log_change','gn_log_search','gn_research' ]
for seed_general in list_general:
print("mapping "+seed_general)
data_json_mapping = await self.read_file_json_mapping(seed_general)
try:
await self.aes.indices.create(index=seed_general, body=data_json_mapping)
except:
print("This file has already been created, and I cannot create it again.")
async def create_mapping_delete(self,location_file_zip:str, app_key="majles"):
locations_data_ok = []
location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/")
location_mapping_general = os.listdir(f"{self.path_mapping}/general/")
location_filezip = os.listdir(location_file_zip)
name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5)
name_locations_mapping_general = await self.name_file(location_mapping_general, 5)
name_locations_filezip = await self.name_file(location_filezip, 4)
for a in name_locations_filezip:
if await self.test_file(name_locations_mapping_majles, a):
print(a)
async with aiofiles.open(f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8") as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif await self.test_file(name_locations_mapping_general, a):
print(a)
async with aiofiles.open(
f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
if a == "mj_rg_section" or a == "semantic_search":
mapping_read = "mj_qa_section"
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif a[-3:] == "_ai":
mapping_read = a[:-3]
try:
async with aiofiles.open(
f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
except:
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
await self.delete_index(a)
await asyncio.sleep(10)
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
print(f"not funds map {a}")
return locations_data_ok
## error for to for
async def create_mapping(self,location_file_zip:str, app_key="majles"):
locations_data_ok = []
location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/")
location_mapping_general = os.listdir(f"{self.path_mapping}/general/")
location_filezip = os.listdir(location_file_zip)
name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5)
name_locations_mapping_general = await self.name_file(location_mapping_general, 5)
name_locations_filezip = await self.name_file(location_filezip, 4)
for a in name_locations_filezip:
if await self.test_file(name_locations_mapping_majles, a):
print(a)
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif await self.test_file(name_locations_mapping_general, a):
print(a)
async with aiofiles.open(
f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
if a == "mj_rg_section" or a == "semantic_search":
mapping_read = "mj_qa_section"
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
elif a[-3:] == "_ai":
mapping_read = a[:-3]
try:
async with aiofiles.open(
f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
except:
async with aiofiles.open(
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
) as file_json:
data_mapping_josn = await file_json.read()
data_mapping_josn = json.loads(data_mapping_josn)
locations_data_ok.append(a)
try:
await self.aes.indices.create(index=a, body=data_mapping_josn)
await self.aes.indices.refresh(index=a)
except:
print(
f" ******************* There is a mapping {a} ***********************"
)
else:
print(f"not funds map {a}")
return locations_data_ok
## error for to for
async def data_unzip(self,location_file_zip:str,namefile: str):
current_directory = os.getcwd()
file_name = f"{location_file_zip}/{namefile}.zip"
sleep(10)
print(" -----> start to unzip ... ",file_name)
data1 = []
os.system(f"del /q /S .\\data\\tmp\\edb\\{namefile}")
os.system(f"mkdir .\\data\\tmp\\edb\\{namefile}")
# os.system(f"del -rf /q .\\data\\tmp\\edb\\{namefile}\\*")
os.system(f"tar -xf {file_name} -C .\\data\\tmp\\edb\\{namefile}\\")
#await asyncio.sleep(1)
list_file_json = os.listdir(f".\\data\\tmp\\edb\\{namefile}\\")
await asyncio.sleep(10)
for a in list_file_json:
try:
with open(f"{current_directory}\\data\\tmp\\edb\\{namefile}\\{a}", "r", encoding="utf8") as file_json:
data = file_json.read()
data = json.loads(data)
for a1 in data:
#await asyncio.sleep(0.001)
try:
yield (
{
"_op_type": "index",
"_index": namefile,
"_id": a1["_id"],
"_source": a1["_source"],
}
)
except:
print("error type document")
except Exception as e:
print(f"read file {current_directory}\\data\\tmp\\edb\\{namefile}\\{a}" + " " + {e})
async def go_to_data(list_data: list, namefile: str):
with open(f"T:{namefile}.json", "a") as a:
a.write(str(list_data))
a.close()
async def run_elastic_import(self,loc:str):
locations_data = await self.create_mapping(loc)
print(locations_data)
await self.create_general_indexes()
#await asyncio.sleep(5)
for file_list in locations_data:
# try :
await async_bulk(self.aes, self.data_unzip(loc,file_list), True)
gc.collect()
# except:
# await asyncio.sleep(10)
# await async_bulk(self.aes, self.data_unzip(file_list), True)
print("finash")
#await asyncio.sleep(10)
async def run_elastic_import_delete(self,loc:str):
locations_data = await self.create_mapping_delete(loc)
#await asyncio.sleep(1000)
print(locations_data)
await self.create_general_indexes()
#await asyncio.sleep(5)
for file_list in locations_data:
# try :
await async_bulk(self.aes, self.data_unzip(loc,file_list), True)
gc.collect()
# except:
# await asyncio.sleep(10)
# await async_bulk(self.aes, self.data_unzip(file_list), True)
print("finash")
#await asyncio.sleep(10)
async def delete_index(self,name_index:str):
await self.aes.indices.delete(index=name_index, ignore=[400, 404]) # await go_to_data( data2,"gn_dataset")
View File
+42
View File
@@ -0,0 +1,42 @@
from dotenv import load_dotenv
import os
import sys
from app.common.elastic_helper import ElasticHelper
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
elastic.exportToJsonForAI(
path_back=r"D:\init_mahdi\dataParsers\data",
index_name="mj_qa_conflict",
out_name="yes_rt_100_data.json",
body={
# "query": {"range": {"conflict_rank.subject_unity_bayes": {"lte": -15}}},
# "query": {"range": {"conflict_rank.subject_unity_bayes": {"gte": 71}}},
# "query": {"range": {"conflict_rank.conflict_detection_bayes": {"gte": 50}}},
# "query": {"range": {"conflict_rank.conflict_detection_bayes": {"lte": -52}}},
# "query": {"range": {"conflict_rank.relation_identification_bayes": {"lte": -20}}},
"query": {"range": {"conflict_rank.relation_identification_bayes": {"gte": 85}}},
},
)
"""
POST mj_qa_conflict/_search
{
"query": {
"range": {
"conflict_rank.subject_unity_bayes": {
"lte": -50
}
}
}
}
"""
# D:\init_mahdi\dataParsers\app\conflict_stuff\get_sample.py
# python -m app.conflict_stuff.get_sample
+214
View File
@@ -0,0 +1,214 @@
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
+67
View File
@@ -0,0 +1,67 @@
from app.common.elastic_helper import ElasticHelper
import os
import orjson
from pathlib import Path
from dotenv import load_dotenv
from elasticsearch.helpers import scan
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)
)
load_dotenv()
url = os.getenv("ES_URL")
user_name = os.getenv("ES_USER_NAME")
password = os.getenv("ES_PASSWORD")
_index = os.getenv("INDEX_NAME")
es_helper = ElasticHelper(
es_pass=password,
es_url=url,
es_user=user_name,
)
es = es_helper.es
fields =[
"_id",
"qanon_id",
"content",
"qanon_title",
"state_etebar",
"qanon_etebar",
"other_info.full_path"
]
result = list(
scan(
es,
index=_index,
query={
"_source": fields,
"query":
{"match_all": {}},
},
)
)
# result= es_helper.es_iterate_all_documents(
# index=_index,
# _source=filed, query={"match_all": {}} # , size=3
# )
print(f'result {len(result)}')
save_orjson(
data=result,
path='./qs_data_for_h100_1.json'
)
# python -m app.import_json_from_es.main
+4 -6
View File
@@ -332,11 +332,11 @@ dict_version_weight = {
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")
# host = os.getenv("HOST_H102") # host = os.getenv("HOST_H102")
@@ -540,8 +540,6 @@ body_test1={
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
## -----------------------------------------------------------------------
## -----------------------------------------------------------------------
+82 -24
View File
@@ -276,7 +276,16 @@ dict_version_weight = {
"deepseek": 1, "deepseek": 1,
"qwopus4_6": 1, "qwopus4_6": 1,
"qwen3_5_122B": 1, "qwen3_5_122B": 1,
"openyourmind": 1, "qwen3_80B": 1,
"gemma4_103": 1,
"deepseek_103": 1,
"oss120_103": 1,
"qwen3_5_103": 1,
"qwen3_6_103": 1,
"qwen3_103": 1,
"qwopus4_6_103": 1,
"yourmind_103": 1,
}, },
"conflict_detections" : { "conflict_detections" : {
"oss120": 0.8, "oss120": 0.8,
@@ -285,7 +294,18 @@ dict_version_weight = {
"deepseek": 1, "deepseek": 1,
"qwopus4_6": 1, "qwopus4_6": 1,
"qwen3_5_122B": 1, "qwen3_5_122B": 1,
"qwen3_80B": 1,
"openyourmind": 1.2, "openyourmind": 1.2,
"gemma4_103": 1,
"deepseek_103": 1,
"oss120_103": 1,
"qwen3_5_103": 1,
"qwen3_6_103": 1,
"qwen3_103": 1,
"qwopus4_6_103": 1,
"yourmind_103": 1,
}, },
"relation_identifications" : { "relation_identifications" : {
"oss120": 0.8, "oss120": 0.8,
@@ -294,7 +314,18 @@ dict_version_weight = {
"deepseek": 1, "deepseek": 1,
"qwopus4_6": 1, "qwopus4_6": 1,
"qwen3_5_122B": 1, "qwen3_5_122B": 1,
"qwen3_80B": 1,
"openyourmind": 1, "openyourmind": 1,
"gemma4_103": 1,
"deepseek_103": 1,
"oss120_103": 1,
"qwen3_5_103": 1,
"qwen3_6_103": 1,
"qwen3_103": 1,
"qwopus4_6_103": 1,
"yourmind_103": 1,
} }
} }
@@ -333,13 +364,12 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map)
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
version_keys_v3 = [ version_keys_v3 = [
"su-gemma4_cd-ri-urmind_e-qwen3.6_285k_group_v3", "su-gemma4_cd-ri-urmind_e-qwen3.6_285k_group_v3"
"su-gemma4_cd-ri-urmind_e-qwen3.6_285k_group_v3-2",
] ]
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
body={ body_v3={
"query":{ "query":{
"terms": { "terms": {
"version_key": version_keys_v3 "version_key": version_keys_v3
@@ -347,16 +377,23 @@ body={
} }
} }
C_avg_su, C_avg_cd, C_avg_rt = compute_avg_all(elastic, "mj_qa_conflict", body) body_103={
# #-------------------------------------------------- "query": {
# #-------------------------------------------------- "nested": {
C_avg_su = 1 "path": "subject_unitys",
C_avg_cd = -1.0745626235324917 "query": {
C_avg_rt = 0.3143402034261242 "term": {
# C_avg_rt = 0.30 "subject_unitys.ref_key": {
"value": "gemma4_103"
}
}
}
}
}
}
body={ body_no_rank={
"query": { "query": {
"bool": { "bool": {
"must":[ "must":[
@@ -364,17 +401,7 @@ body={
"terms": { "terms": {
"version_key": version_keys_v3 "version_key": version_keys_v3
} }
},
{
"nested": {
"path": "conflict_evaluations",
"query": {
"exists": {
"field": "conflict_evaluations.main_type"
}
}
} }
}
], ],
"must_not": [ "must_not": [
{ {
@@ -389,8 +416,39 @@ body={
} }
re_compute_conflict_ranks(elastic, "mj_qa_conflict", C_avg_su, C_avg_cd, C_avg_rt, 3, body) # C_avg_su, C_avg_cd, C_avg_rt = compute_avg_all(elastic, "mj_qa_conflict", body_v3)
# re_compute_conflict_ranks(elastic, "mj_qa_conflict", C_avg_su, C_avg_cd, C_avg_rt, 3, {}) # #--------------------------------------------------
# #----- subject_unity total_vote, total_count, avge : 283938.199999187 314203 0.9036775587731085
# #----------
# #----- conflict_detections total_vote, total_count, avge : -337630.80000177945 314203 -1.0745626235324917
# #----------
# #----- conflict_relation_identifications total_vote, total_count, avge : 41412.600000000915 114953 0.3602568006054728
# #--------------------------------------------------
# #--------------------------------------------------
# #----- subject_unity total_vote, total_count, avge : 350754.3999994566 663381 0.528737482682586
# #----------
# #----- conflict_detections total_vote, total_count, avge : -891082.9999999751 994299 -0.8961921916847699
# #----------
# #----- conflict_relation_identifications total_vote, total_count, avge : 83677.40000002725 158600 0.5276002522069814
# #--------------------------------------------------
C_avg_su = 0.528737482682586
# C_avg_cd = -1.0745626235324917
C_avg_cd = 0
C_avg_rt = 0.5276002522069814
### -----103 بسته -----------
# C_avg_su = 0.1315904139433552
# C_avg_cd = 0.09096573208722765
# C_avg_rt = 0.6596421471172959
# re_compute_conflict_ranks(elastic, "mj_qa_conflict", C_avg_su, C_avg_cd, C_avg_rt, 3, body_103)
### ---------------------------
# re_compute_conflict_ranks(elastic, "mj_qa_conflict", C_avg_su, C_avg_cd, C_avg_rt, 3, body_no_rank)
re_compute_conflict_ranks(elastic, "mj_qa_conflict", C_avg_su, C_avg_cd, C_avg_rt, 3, body_v3)
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
@@ -1,569 +0,0 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import zipfile
import pandas as pd
import asyncio
import multiprocessing
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 run_to_procssing(list_files, index_name, file_jumps, host, password):
results = []
for file in list_files:
result = asyncio.run( import_data_from_json( file, index_name, file_jumps, host, password))
results.append(result)
return results
async def pack_files_to_elastic(
input_path, index_name, file_jumps, host, password
):
list_files = []
if os.path.isdir(input_path):
list_files = [
os.path.join(input_path, f)
for f in os.listdir(input_path)
if os.path.isfile(os.path.join(input_path, f))
]
elif os.path.isfile(input_path):
list_files.append(input_path)
jump_files = []
if os.path.exists(file_jumps):
with open(file_jumps, "r", encoding="utf-8") as f:
jump_files = [line.strip() for line in f if line.strip()]
list_input = []
for file in list_files:
if not file in jump_files:
list_input.append(file)
# ----------------------------------------
# ---- packing by cpu_count --------------
cpu_count = 10
list_process = []
x = len(list_input)
y = (x - (x % cpu_count)) / cpu_count
c = x % cpu_count
list_spilt = []
for f in range(0, x, int(y)):
list_spilt.append(f)
list_spilt[len(list_spilt) - 1] = list_spilt[len(list_spilt) - 1] + c
b = 0
len_list_spilt = len(list_spilt)
for split in list_spilt:
if b + 1 < len_list_spilt:
print(split, list_spilt[b + 1])
proc = multiprocessing.Process(
target=run_to_procssing,
args=(
list_input[split : list_spilt[b + 1]],
index_name,
file_jumps,
host,
password,
),
)
proc.start()
list_process.append(proc)
b = b + 1
for proc in list_process:
proc.join()
print("finish ⏹️✅")
async def import_data_from_json(file, index_name, file_jumps, host, password) -> list:
time = datetime.datetime.now().timestamp()
file_name = file.split("/")[-1:][0]
print("▶️", file_name)
elastic = ElasticHelper(
es_url=host, es_pass=password, es_user="elastic"
)
data_all = []
try:
with open(file, "rb") as rfile:
data_all = json.loads(rfile.read())
if data_all[0] and isinstance(data_all[0], list):
data_all = data_all[0]
except Exception as e:
print(f"not read file {file}", str(e))
bulk_data = []
failed_data = []
total_count = 0
list_jump = []
for item in data_all:
_id = item["id"]
previous_info = item["previous_info"]
next_info = item["next_info"]
# version_key = item["version_key"]
version_key = "su-gemma4_cd-ri-urmind_e-qwen3.6_285k_group_v3-2"
subject_unity = item["subject_unity"]
if subject_unity["main_type"] == "no":
continue
qanon_title1 = previous_info["qanon_title"]
qanon_id1 = previous_info["qanon_id"]
qanon_title2 = next_info["qanon_title"]
qanon_id2 = next_info["qanon_id"]
title_type1 = getTitleType(qanon_title1)
title_type2 = getTitleType(qanon_title2)
previous_info["title_type"] = title_type1
next_info["title_type"] = title_type2
conflict_detection = item["conflict_detection"]
# conflict_type_detection = item["conflict_type_detection"]
conflict_relation_identification = item["conflict_relation_type"]
conflict_evaluation = item["conflict_evaluation"]
conflict_final = item["conflict_final"]
subject_unity["ref_key"] = "gemma4"
es_data = {
"id": _id,
"version_key": version_key,
"previous_info": previous_info,
"next_info": next_info,
"subject_unitys": [subject_unity],
}
if conflict_detection:
conflict_detection["ref_key"] = "openyourmind"
es_data["conflict_detections"] = [conflict_detection]
if conflict_relation_identification:
conflict_relation_identification["ref_key"] = "openyourmind"
es_data["conflict_relation_identifications"] = [
conflict_relation_identification
]
if conflict_evaluation:
conflict_evaluation["ref_key"] = "qwen3-6"
es_data["conflict_evaluations"] = [conflict_evaluation]
if conflict_final:
es_data["conflict_finals"] = [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) + " -- " + str(total_import))
elastic.importBulkList(bulk_data, index_name)
bulk_data = []
if len(bulk_data) > 0:
# total_count += len(bulk_data)
# print("=" * 10, "to_elastic , total=" + str(total_count) + " -- " + str(total_import))
elastic.importBulkList(bulk_data, index_name)
bulk_data = []
with open(file_jumps, "w") as f:
f.write("\n"+file)
# total_import += total_count
time1 = datetime.datetime.now().timestamp()
time = time1 - time
print("✅", file_name, ":", time)
def clear_array_object_by(array, ref_key):
array = [c for c in array if c["ref_key"] != ref_key]
# تغییر کلید و حذف اضافات قبلی
# array = [c for c in array if (c["ref_key"] != "oss120-p2-v2" and c["ref_key"] != "gemma4-p2-v2" )]
return array
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 genrate_excel_data(
elastic,
file_ouput,
index_name_o="mj_qa_conflict",
key="subject_unitys",
key_value="qwen3-6",
base_url="http://192.168.23.160",
):
body = {
"query": {
"bool": {
"must": [
{
"nested": {
"path": key,
"query": {"term": {key + ".ref_key": {"value": key_value}}},
}
}
]
}
},
"sort": [{"previous_info.ts_date": "desc"}],
}
print(body)
columns = [
"ردیف",
"شناسه",
"لینک",
"وحدت موضوع خبره",
"توضیح خبره",
"امتیاز ماشینی",
"وحدت موضوع oss120",
"وحدت موضوع qwen3-6",
"وحدت موضوع gemma4-p2",
"وحدت موضوع oss120-p2",
"وحدت موضوع qwen3-6-p2",
"وحدت موضوع openyourmind",
"تخالف حکمی خبره",
"توضیح خبره",
"امتیاز ماشینی",
"تخالف حکمی oss120",
"تخالف حکمی qwen3-6",
"تخالف حکمی gemma4-p2",
"تخالف حکمی oss120-p2",
"تخالف حکمی qwen3-6-p2",
"تخالف حکمی openyourmind",
"نوع رابطه خبره",
"توضیح خبره",
"امتیاز ماشینی",
"نوع رابطه oss120",
"نوع رابطه qwen3-6",
"نوع رابطه gemma4-p2",
"نوع رابطه oss120-p2",
"نوع رابطه qwen3-6-p2",
"نوع رابطه openyourmind",
"ارزیابی آخر خبره",
"توضیح خبره",
"امتیاز ماشینی",
"ارزیابی آخر oss120",
"ارزیابی آخر qwen3-6",
"ارزیابی آخر gemma4-p2",
"ارزیابی آخر oss120-p2",
"ارزیابی آخر qwen3-6-p2",
"ارزیابی آخر openyourmind",
]
# Create DataFrame with column names
try:
list_ = elastic.es_iterate_all_documents(index_name_o, body)
except Exception as e:
print(str(e))
return
# data_out = [
# ["John", 25, "New York"],
# ["Sarah", 30, "London"],
# ["Mike", 28, "Toronto"],
# ["Emma", 35, "Sydney"],
# ]
data = list(list_)
total = len(data)
count = 0
total_count = 0
print(total)
data_out = []
for mentry in data:
count += 1
entry = mentry["source"]
_id = entry.get("id", "")
print(_id)
next_info = entry.get("next_info", {})
previous_info = entry.get("previous_info", {})
subject_unitys = entry.get("subject_unitys", {})
conflict_detections = entry.get("conflict_detections", {})
conflict_type_detections = entry.get("conflict_type_detections", {})
conflict_relation_identifications = entry.get(
"conflict_relation_identifications", {}
)
conflict_evaluations = entry.get("conflict_evaluations", {})
conflict_finals = entry.get("conflict_finals", {})
link = f'=HYPERLINK("{base_url}/refine/conflict/{_id}", "لینک")'
subject_rate = 0
subject_oss120 = ""
subject_qwen3_6 = ""
subject_gemma4_p2 = ""
subject_oss120_p2 = ""
subject_qwen3_6p2 = ""
subject_openyourmind = ""
for su in subject_unitys:
if su["ref_key"] == "oss120":
subject_oss120 = su["main_type"]
# subject_rate += getRate(su["main_type"])
if su["ref_key"] == "qwen3-6":
subject_qwen3_6 = su["main_type"]
subject_rate += getRate(su["main_type"])
if su["ref_key"] == "gemma4-p2":
subject_gemma4_p2 = su["main_type"]
subject_rate += getRate(su["main_type"])
if su["ref_key"] == "oss120-p2":
subject_oss120_p2 = su["main_type"]
subject_rate += getRate(su["main_type"])
if su["ref_key"] == "qwen3-6-p2":
subject_qwen3_6p2 = su["main_type"]
subject_rate += getRate(su["main_type"])
if su["ref_key"] == "openyourmind":
subject_openyourmind = su["main_type"]
subject_rate += getRate(su["main_type"])
conflict_rate = 0
conflict_oss120 = ""
conflict_qwen3_6 = ""
conflict_gemma4_p2 = ""
conflict_oss120_p2 = ""
conflict_qwen3_6p2 = ""
conflict_openyourmind = ""
for su in conflict_detections:
if su["ref_key"] == "oss120":
conflict_oss120 = str(su["has_conflict"])
# conflict_rate += getRate(su["has_conflict"])
if su["ref_key"] == "qwen3-6":
conflict_qwen3_6 = str(su["has_conflict"])
conflict_rate += getRate(su["has_conflict"])
if su["ref_key"] == "gemma4-p2":
conflict_gemma4_p2 = str(su["has_conflict"])
conflict_rate += getRate(su["has_conflict"])
if su["ref_key"] == "oss120-p2":
conflict_oss120_p2 = str(su["has_conflict"])
conflict_rate += getRate(su["has_conflict"])
if su["ref_key"] == "qwen3-6-p2":
conflict_qwen3_6p2 = str(su["has_conflict"])
conflict_rate += getRate(su["has_conflict"])
if su["ref_key"] == "openyourmind":
conflict_openyourmind = str(su["has_conflict"])
conflict_rate += getRate(su["has_conflict"])
relation_rate = 0
relation_oss120 = ""
relation_qwen3_6 = ""
relation_gemma4_p2 = ""
relation_oss120_p2 = ""
relation_qwen3_6p2 = ""
relation_openyourmind = ""
for su in conflict_relation_identifications:
if su["ref_key"] == "oss120":
relation_oss120 = su["main_type"]
# relation_rate += getRate(su["main_type"])
if su["ref_key"] == "qwen3-6":
relation_qwen3_6 = su["main_type"]
relation_rate += getRate(su["main_type"])
if su["ref_key"] == "gemma4-p2":
relation_gemma4_p2 = su["main_type"]
relation_rate += getRate(su["main_type"])
if su["ref_key"] == "oss120-p2":
relation_oss120_p2 = su["main_type"]
relation_rate += getRate(su["main_type"])
if su["ref_key"] == "qwen3-6-p2":
relation_qwen3_6p2 = su["main_type"]
relation_rate += getRate(su["main_type"])
if su["ref_key"] == "openyourmind":
relation_openyourmind = su["main_type"]
relation_rate += getRate(su["main_type"])
evalution_rate = 0
evalution_oss120 = ""
evalution_qwen3_6 = ""
evalution_gemma4_p2 = ""
evalution_oss120_p2 = ""
evalution_qwen3_6p2 = ""
evalution_openyourmind = ""
for su in conflict_evaluations:
if su["ref_key"] == "qwen3-6":
evalution_oss120 = su["main_type"]
# evalution_rate += getRate(su["main_type"])
if su["ref_key"] == "qwen3-6":
evalution_qwen3_6 = su["main_type"]
evalution_rate += getRate(su["main_type"])
if su["ref_key"] == "gemma4-p2":
evalution_gemma4_p2 = su["main_type"]
evalution_rate += getRate(su["main_type"])
if su["ref_key"] == "oss120-p2":
evalution_oss120_p2 = su["main_type"]
evalution_rate += getRate(su["main_type"])
if su["ref_key"] == "qwen3-6-p2":
evalution_qwen3_6p2 = su["main_type"]
evalution_rate += getRate(su["main_type"])
if su["ref_key"] == "openyourmind":
evalution_openyourmind = su["main_type"]
evalution_rate += getRate(su["main_type"])
item = [
str(count),
_id,
link,
"",
"",
subject_rate,
subject_oss120,
subject_qwen3_6,
subject_gemma4_p2,
subject_oss120_p2,
subject_qwen3_6p2,
subject_openyourmind,
"",
"",
conflict_rate,
conflict_oss120,
conflict_qwen3_6,
conflict_gemma4_p2,
conflict_oss120_p2,
conflict_qwen3_6p2,
conflict_openyourmind,
"",
"",
relation_rate,
relation_oss120,
relation_qwen3_6,
relation_gemma4_p2,
relation_oss120_p2,
relation_qwen3_6p2,
relation_openyourmind,
"",
"",
evalution_rate,
evalution_oss120,
evalution_qwen3_6,
evalution_gemma4_p2,
evalution_oss120_p2,
evalution_qwen3_6p2,
evalution_openyourmind,
]
print(item)
data_out.append(item)
df = pd.DataFrame(data_out, columns=columns)
# Save to Excel
df.to_excel(file_ouput, index=False)
def getRate(main_type):
if main_type == "yes":
return 1
elif main_type == "yes_under_assumptions":
return 0.7
elif main_type == "no":
return 0
elif main_type == True:
return 1
else:
return 0
## -----------------------------------------------------------------------
# .\.env\Scripts\activate
# python -m app.majles.majles_conflict_works_async_v3
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")
print(".... host ......", host)
## ----------------------------------------------------
# path_base_map = "G:/Project2/tavasi_160/src/repo/_other/"
# elastic = ElasticHelper(es_url=f"http://{host}:6900",es_pass= password,es_user= "elastic", path_mappings=path_base_map)
# map_file = "G:/Project2/tavasi_160/src/repo/_other/majles/mj_qa_conflict.json"
# elastic.createIndex(index_name="mj_qa_conflict",map_name="mj_qa_conflict",mapping_file_path=map_file)
# elastic.es.close()
input_path = r"G:\Project2\102_gpu\v3_conflict\285k_group_v3"
file_jumps = r"G:\Project2\102_gpu\v3_conflict\285k_group_v3_jump_files.json"
asyncio.run(
pack_files_to_elastic(
input_path, "mj_qa_conflict", file_jumps, host, password
)
)
+5 -6
View File
@@ -913,11 +913,11 @@ def getRate(main_type):
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")
print(".... majles_codes_update_steps ......", host) print(".... majles_codes_update_steps ......", host)
@@ -1166,7 +1166,6 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map)
# ref_key="yourmind-p3") # ref_key="yourmind-p3")
# # #---------------------------------------------------------------------------------------------- # # #----------------------------------------------------------------------------------------------
# # #---------------------------------------------------------------------------------------------- # # #----------------------------------------------------------------------------------------------
# # #---------------------------------------------------------------------------------------------- # # #----------------------------------------------------------------------------------------------
@@ -1177,4 +1176,4 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map)
## ----------------------------------------------------------------------- ## -----------------------------------------------------------------------
# .\.env\Scripts\activate # .\.env\Scripts\activate
# python -m app.majles.majles_conflict_works # python -m app.majles.majles_conflict_works_v2
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+64
View File
@@ -0,0 +1,64 @@
from app.common.elastic_helper import ElasticHelper
import os
import orjson
from pathlib import Path
from dotenv import load_dotenv
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)
)
meet_index_name = "mn_meet"
dash = "-" * 25
load_dotenv()
url = os.getenv("ES_URL")
user_name = os.getenv("ES_USER_NAME")
password = os.getenv("ES_PASSWORD")
new_data = load_orjson(r"D:\init_mahdi\project\dataParsers\app\monir\p1_changed_id_item.json")
print(f'new_data {len(new_data)}')
es_helper = ElasticHelper(
es_url=url,
es_user=user_name,
es_pass=password,
# path_mappings = ""
)
sussecfull = 0
failed = 0
for id, item in new_data.items():
db_data = es_helper.get_document(index_name=meet_index_name, id=id)
# print(f'db_data {db_data}')
db_data = db_data['_source']
if db_data['content'] == item["meet_content"]:
failed += 1
continue
elif item["meet_content"] == "":
failed += 1
continue
else:
sussecfull +=1
db_data['html'] = db_data['content']
db_data['content'] = item["meet_content"]
es_helper.update_index_doc(is_update_state=True, index_name_o=meet_index_name, eid=id, data=db_data)
print(f'id {id}')
# break
# print(db_data)
print(
f'sussecfull {sussecfull}',
f'failed {failed}',
)
# python -m app.monir.change_content_html_meet
# 6235
# sussecfull 139 failed 6096
+373
View File
@@ -0,0 +1,373 @@
from bs4 import BeautifulSoup
import orjson
from pathlib import Path
import re, os, traceback, html
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 html_to_clean_text(html: str) -> str:
"""
Parse HTML 2 PLAIN TEXT
"""
soup = BeautifulSoup(html, "html.parser")
# تبدیل تگ‌های ساختاری به newline
for tag in soup.find_all(["br", "p", "h1", "h2", "h3", "h4", "h5", "h6"]):
tag.append("\n")
# حذف همه‌ی استایل‌ها و تگ‌های اضافی
for tag in soup():
if tag.name not in ["a"]:
tag.attrs = {} # remove style, class, dir, etc.
# استخراج متن خام
text = soup.get_text("\n")
# حذف newline های اضافی
text = re.sub(r"\n{2,}", "\n", text)
# حذف فاصله‌های خاص HTML
text = text.replace("\xa0", " ").strip()
return text
HTML_TO_NEWLINE = [
r"<\s*br\s*/?>",
r"<\s*p[^>]*>",
r"<\s*/\s*p\s*>",
r"<\s*h[1-6][^>]*>",
r"<\s*/\s*h[1-6]\s*>",
r"<\s*div[^>]*>",
r"<\s*/\s*div\s*>",
]
HTML_TO_SPACE = [
r"&nbsp;",
r"<\s*span[^>]*>",
r"<\s*/\s*span\s*>",
r"\u00A0",
]
def clean_remaining_markup_junk(text: str) -> str:
# 1 orphan closing VML tags </v:...>
text = re.sub(r"</\s*v:[^>]+>", "", text, flags=re.IGNORECASE)
# 2 orphan closing Office tags </o:...>
text = re.sub(r"</\s*o:[^>]+>", "", text, flags=re.IGNORECASE)
# 3 broken SUP tag: SUP>1</SUP>
text = re.sub(r"\bSUP>\s*\d+\s*</\s*SUP\s*>", "", text, flags=re.IGNORECASE)
# 4 FONT tag با محتوای فقط whitespace
text = re.sub(r"<\s*font[^>]*>\s*</\s*font\s*>", "", text, flags=re.IGNORECASE)
return text
def clean_broken_formatting_tags(text: str) -> str:
# 1 fragment های شکسته مثل <STRON ، <B ، <U
text = re.sub(
r"<\s*(strong|stron|b|u|i)\b[^\>]*$",
"",
text,
flags=re.IGNORECASE | re.MULTILINE,
)
# 2 تگ های فرمت‌دهی که باز شده‌اند ولی فقط newline/space بعدش آمده
text = re.sub(r"<\s*(strong|b|u|i)[^>]*>\s*(?=\n)", "", text, flags=re.IGNORECASE)
# 3 orphan opening formatting tags
text = re.sub(r"<\s*(strong|b|u|i)[^>]*>", "", text, flags=re.IGNORECASE)
# 4 <BR> با هر attribute → newline
text = re.sub(r"<\s*br\b[^>]*>", "\n", text, flags=re.IGNORECASE)
return text
def clean_word_office_tag(text: str) -> str:
# 1 XML namespace
text = re.sub(r"<\?xml:namespace[^>]*?>", "", text, flags=re.IGNORECASE)
# 2 Office tags
text = re.sub(r"<\s*o:[^>]+>|<\s*/\s*o:[^>]+>", "", text, flags=re.IGNORECASE)
# 3 VML
text = re.sub(
r"<\s*v:[^>]+>.*?<\s*/\s*v:[^>]+>", "", text, flags=re.IGNORECASE | re.DOTALL
)
text = re.sub(r"<\s*v:[^>]*/\s*>", "", text, flags=re.IGNORECASE)
# 4 حذف کامل لینک‌های فهرست Word (کلیدی)
text = re.sub(
r"<\s*a[^>]*_Toc[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
# 5 حذف تگ‌های فرمت‌دهی خالی
text = re.sub(r"<(strong|b|u|i)[^>]*>\s*</\1>", "", text, flags=re.IGNORECASE)
# orphan closing tags
text = re.sub(r"</\s*(strong|b|u|i|a)\s*>", "", text, flags=re.IGNORECASE)
return text
def clean_text(text: str) -> str:
# 1 فقط entity ها (بدون حذف هیچ تگی)
text = html.unescape(text)
# 2 تگ‌های newline
for pattern in HTML_TO_NEWLINE:
text = re.sub(pattern, "\n", text, flags=re.IGNORECASE)
# 3 موارد فاصله‌ای
for pattern in HTML_TO_SPACE:
text = re.sub(pattern, " ", text, flags=re.IGNORECASE)
# 4 نرمال‌سازی فاصله‌های اطراف newline
# " \n" , "\n " , " \n "
text = re.sub(r"[ \t]+\n", "\n", text)
text = re.sub(r"\n[ \t]+", "\n", text)
# 5 نرمال‌سازی فاصله‌های پشت سرهم
# فاصله‌ها (space) پشت هم ≥2 → یک space
text = re.sub(r" {2,}", " ", text)
# tab پشت سر هم ≥1 → یک tab
text = re.sub(r"\t+", "\t", text)
# 6 جمع کردن newline های پشت‌سرهم
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def clean_inline_font_and_footnote(text: str) -> str:
# 1 پاورقی‌های Word (mso-footnote)
text = re.sub(
r"<\s*a[^>]*mso-footnote-id[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
# 2 FONT هایی که فقط whitespace دارند
text = re.sub(r"<\s*font[^>]*>\s*</\s*font\s*>", "", text, flags=re.IGNORECASE)
# 3 FONT با متن واقعی → نگه‌داشتن متن
text = re.sub(
r"<\s*font[^>]*>([^<]+)</\s*font\s*>", r"\1", text, flags=re.IGNORECASE
)
# 4 SUP های تو در تو (inline reference)
text = re.sub(
r"<\s*sup[^>]*>\s*(?:<\s*sup[^>]*>)?\s*\[?\s*\d+\s*\]?\s*(?:</\s*sup\s*>)?\s*</\s*sup\s*>",
"",
text,
flags=re.IGNORECASE,
)
# 5 tab / shift-space / NBSP
text = text.replace("\t", " ")
text = re.sub(r"\u00A0+", " ", text)
return text
def clean_xml_noise(text: str) -> str:
# 1 حذف namespace های XML ورد
text = re.sub(r"<\?xml:namespace[^>]*?>", "", text, flags=re.IGNORECASE)
# 2 حذف تگ های o:p
text = re.sub(r"<\s*o:p\s*>|<\s*/\s*o:p\s*>", "", text, flags=re.IGNORECASE)
# 3 تبدیل NBSP واقعی به space معمولی
for pattern in HTML_TO_SPACE:
text = re.sub(pattern, " ", text, flags=re.IGNORECASE)
# 4 جمع کردن NBSP + newline های پشت سرهم
text = re.sub(r"( \n)+", "\n", text)
text = re.sub(r"\n( \n)+", "\n\n", text)
return text
def clean_final_word_junk(text: str) -> str:
# حذف همه <A> های پاورقی یا anchor Word حتی بدون محتوای قابل نمایش
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor)[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
# orphan <A ...> که بسته نشده یا فقط فضا دارند
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor)[^>]*\s*/?>",
"",
text,
flags=re.IGNORECASE,
)
# 3 حذف <A style="mso-comment-..."> (comment anchor)
text = re.sub(
r"<\s*a[^>]*mso-comment-[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"<\s*a[^>]*mso-comment-[^>]*/\s*>", "", text, flags=re.IGNORECASE)
# 4 حذف DEL (متن حذف‌شده Track Changes)
text = re.sub(
r"<\s*del[^>]*>.*?<\s*/\s*del\s*>", "", text, flags=re.IGNORECASE | re.DOTALL
)
# 5 حذف wrapهای Word
text = re.sub(
r"<\s*w:wrap[^>]*>.*?<\s*/\s*w:wrap\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"<\s*w:wrap[^>]*/\s*>", "", text, flags=re.IGNORECASE)
# 6 حذف HR ها
text = re.sub(r"<\s*hr\b[^>]*>", "", text, flags=re.IGNORECASE)
# 7 حذف تگ‌های قالب‌بندی جدول
text = re.sub(r"<\s*(table|tbody|tr|td)[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(table|tbody|tr|td)\s*>", "", text, flags=re.IGNORECASE)
# 8 حذف orphan / fragment تگ‌های VML و Office
text = re.sub(r"<\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
return text
def clean_final2_word_junk(text: str) -> str:
# 1 حذف تمام <A> های Word (footnote, anchor, endnote)
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor|mso-endnote-id)[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor|mso-endnote-id)[^>]*/?\s*>",
"",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"<\s*(del|ins)[^>]*>.*?<\s*/\s*\1\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(
r"<\s*(em|strong|b|u|i)[^>]*>\s*</\s*\1\s*>", "", text, flags=re.IGNORECASE
)
text = re.sub(r"<\s*font[^>]*>\s*</\s*font\s*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(
r"<\s*w:wrap[^>]*>.*?<\s*/\s*w:wrap\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"<\s*w:wrap[^>]*/\s*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<\s*hr\b[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<\s*(table|tbody|tr|td)[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(table|tbody|tr|td)\s*>", "", text, flags=re.IGNORECASE)
return text
def clean_final_stage(text: str) -> str:
"""
"""
def has_fa_ar(text_chunk: str) -> bool:
# Unicode فارسی: \u0600-\u06FF, عربی: \u0750-\u077F, \u08A0-\u08FF
return bool(re.search(r"[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]", text_chunk))
# <tag ...>...</tag>
def replace_tag(match):
inner = match.group(2) # متن داخل تگ
if has_fa_ar(inner):
return f"({inner.strip()})" # متن فارسی/عربی → داخل پرانتز
else:
return "" # تگ بدون متن فارسی/عربی → حذف کامل
# تگ‌های باز و بسته
text = re.sub(
r"(<([a-zA-Z0-9:_-]+)[^>]*>)(.*?)(</\2>)", replace_tag, text, flags=re.DOTALL
)
text = re.sub(r"<[a-zA-Z0-9:_-]+[^>]*/>", "", text)
text = re.sub(r"<[^>]+>", "", text)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
if __name__ == "__main__":
######################################################################## p1
in_data = load_orjson(
"/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p0_data_dict_id_item.json"
)
unwanted_char = set("&<>")
new_dict = {}
for k, v in in_data.items():
content = v["meet_content"]
if content == "": continue
content = clean_broken_formatting_tags(content)
content = clean_word_office_tag(content)
content = clean_xml_noise(content)
content = clean_remaining_markup_junk(content)
content = clean_inline_font_and_footnote(content)
content = clean_final_word_junk(content)
content = clean_final2_word_junk(content)
content = clean_final_stage(content)
content = clean_text(content)
v["meet_content"] = content
new_dict[k] = v
print(f'new_dict {len(new_dict)}')
save_orjson(
data=new_dict,
path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p1_data_dict_id_item.json",
)
+59
View File
@@ -0,0 +1,59 @@
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
import os
import time, traceback, uuid, orjson
from elasticsearch.helpers import scan
from dotenv import load_dotenv
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)
)
load_dotenv()
url = os.getenv("ES_URL")
user_name = os.getenv("ES_USER_NAME")
password = os.getenv("ES_PASSWORD")
term_index_name = "mn_term"
meet_index_name = "mn_meet"
ment_index_name = "mn_meet_entity"
dash = "-" * 25
es_helper = ElasticHelper(
es_url=url,
es_user="elastic",
es_pass=password,
# path_mappings = ""
)
fields = [ "content", "subtitle", "title", "sanad_id", "id", "main_type", "sub_type"]
es_helper
print(f"fields {fields}")
# fields ['id', 'sort_date_timestamp', 'title', 'subtitle', 'research_code', 'content', 'version_info', 'meet_lid', 'meet_id', 'meet_no', 'meet_code', 'allwords', 'keywords', 'person_code', 'subject', 'city', 'author', 'begin_year', 'begin_date', 'end_date', 'branch', 'ralation', 'research_id', 'mintro', 'mindex', 'RowNum', 'resource_info', 'in_tadvin', 'format', 'verb', 'address', 'attendees', 'amplify', 'audience', 'place', 'permit_tags', 'photos', 'tags', 'films', 'sounds', 'file_links', 'sound_links', 'video_links', 'photo_links']
es = es_helper.es
# old_data = es_helper.search(
# index=old_index_name, _source=fields, query={"match_all": {}}, size=3
# )
# old_data = old_data["hits"]["hits"] # don't use in scan
################### for all data
old_data = list(
scan(
es,
index="mn_meet",
query={
"_source": fields,
"query":
# {"ids": {"values": ["pm146821"]}},
{"match_all": {}},
},
)
)
print(f'old_data {len(old_data)}')
save_orjson(
data=old_data,
path=r"./mn_meet_for_section.json"
)
# python -m dataParsers.app.monir.test
+64
View File
@@ -0,0 +1,64 @@
from dotenv import load_dotenv
import os
import sys
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
from pydantic import BaseModel
from typing import List
from pathlib import Path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
print(f"host {host} password {password}")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def create_data(
_index_name: str,
input_path: Path,
bulk_size=200,
):
f_data = []
f_counter = 0
# input_data = DataHelper.load_orjson(
# # r"D:\init_mahdi\dataParsers\data\index_image_11k.json"
# r"D:\init_mahdi\dataParsers\data\monir_mn_voice_sanad.json"
# )
for data_path in Path(input_path).rglob("*.json"):
input_data = DataHelper.load_orjson(data_path)
for data in input_data:
f_data.append({"_id": data["_id"], "_source": data["_source"]})
if len(f_data) >= bulk_size:
f_counter += len(f_data)
elastic.importBulkList(listData=f_data, index_name=_index_name)
print(f"---- {f_counter}/{len(input_data)} ----")
f_data = []
if len(f_data) > 0:
f_counter += len(f_data)
elastic.importBulkList(listData=f_data, index_name=_index_name)
print(f"---- {f_counter}/{len(input_data)} ----")
f_data = []
print(":D")
create_data(
# _index_name="monir_ocr_lib",
# _index_name="monir_mn_voice_sanad",
_index_name="majles_group_mashruh",
input_path=Path(r"D:\init_mahdi\dataParsers\data\index_mashruh_group"),
)
# source $HOME/.dataParsers/bin/activate
# cd /home/sabr/dataParsers
# python3 -m app.put_data_ocr
# python -m app.put_data_ocr
+165
View File
@@ -0,0 +1,165 @@
from dotenv import load_dotenv
import os, sys, re
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
from pydantic import BaseModel
from typing import Literal, List, Dict, Any, Optional
from pathlib import Path
from elasticsearch import helpers
from elasticsearch.helpers import scan
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
print(f"host {host} password {password}")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def creat_index(
elastic: ElasticHelper,
input_path=Path(
r"D:\init_mahdi\dataParsers\data\mj_qa_group_25315.json"
),
index_name="majles_mj_qa_context",
batch_size=1000,
):
"""
Update existing Elasticsearch documents with embeddings.
Each JSON file must contain:
{
"id": "...",
"emb": [...]
}
The document with the corresponding _id must already exist in Elasticsearch.
"""
actions = []
total = 0
success = 0
failed = 0
print("=" * 80)
print("START BULK EMBEDDING UPDATE")
print(f"Index : {index_name}")
print(f"Input path : {input_path}")
print(f"Batch size : {batch_size}")
print("=" * 80)
in_data = DataHelper.load_orjson(input_path)
# in_data = list(input_path.rglob("*.json"))
print(f"in_data {len(in_data)}")
############################################################
query = {
"_source": ["id"],
"query": {
"bool": {
"filter": [{"term": {"version_key": "base_v3"}}],
"must": [{"exists": {"field": "owl"}}],
}
},
}
process_ids = set(
hit["_id"]
for hit in scan(
elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید
# index="majles_mj_qa_rule",
index="majles_mj_qa_context",
query=query,
size=1000,
)
)
print(f"process_ids {len(process_ids)} => ")
# print(f"process_ids {len(process_ids)} => {list(process_ids)[1]}")
############################################################
for data in in_data:
try:
# data = DataHelper.load_orjson(j_path)
doc_id = data["_id"]
# embedding = data["embed"]
owl = data["_source"]["owl"]
if doc_id in process_ids:
# print(f"doc_id {doc_id}")
continue
# doc_id = re.sub(r"(_v3)(\d+)$", r"\1-\2", data["id"])
# print(f"doc_id {doc_id}")
# return
action = {
"_op_type": "update",
"_index": index_name,
"_id": doc_id,
"doc": {"owl": owl},
}
actions.append(action)
total += 1
# Send batch
if len(actions) >= batch_size:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print(
f"processed={total:,} | "
f"success={success:,} | "
f"failed={failed:,}"
)
actions.clear()
except Exception as e:
failed += 1
print(f" {type(e).__name__}: {e}")
# Remaining documents
if actions:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print()
print("=" * 80)
print("BULK UPDATE FINISHED")
print(f"Total : {total:,}")
print(f"Success: {success:,}")
print(f"Failed : {failed:,}")
print("=" * 80)
creat_index(elastic=elastic)
# cd D:\init_mahdi\dataParsers\
# python -m app.put_owl_data
+67
View File
@@ -0,0 +1,67 @@
from dotenv import load_dotenv
import os
import sys
from app.common.elastic_helper import ElasticHelper
from elasticsearch.helpers import scan
from pathlib import Path
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
query1 = {
"_source": ["context"],
"query": {
"bool": {
"filter": [{"term": {"version_key": "base_v3"}}],
"must": [{"exists": {"field": "context"}}],
# "must_not": [{"exists": {"field": "embedding"}}],
}
},
}
query = {
"_source": ["content"],
"query": {
"bool": {
"filter": [{"term": {"version_key": "base_v3"}}],
"must_not": [
{"terms": {"title": ["موخره", "امضاء", "عنوان", "فصل", "مبحث"]}}
],
}
},
}
documents = [
# {
# "id": hit["_id"],
# "content": hit["_source"]["content"],
# "qanon_title":hit["_source"]["qanon_title"],
# "rule_type":hit["_source"]["rule_type"],
# }
hit
for hit in scan(
elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید
# index="majles_mj_qa_rule",
index="majles_mj_qa_context",
query=query1,
size=1000,
)
]
print(f"documents {len(documents)}")
elastic.save_orjson(
path=Path(r"D:\init_mahdi\dataParsers\data\embed_listwise\majles_mj_qa_context_context.json"), data=documents
)
# cd dataParsers
# python -m app.save_content_id
+71
View File
@@ -0,0 +1,71 @@
# import mariadb
from dotenv import load_dotenv
import os
import sys
from app.common.elastic_helper import ElasticHelper
from elasticsearch import helpers
from elasticsearch.helpers import scan
from app.common.data_helper import DataHelper
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
# elastic.backup_entire_index(
# index_name="majles_mj_qa_rule",
# output_dir=r"D:\init_mahdi\dataParsers\data\majles_mj_qa_rule",
# batch_size=50000
# )
# elastic.backup_entire_index(
# index_name="majles_mj_qa_context",
# output_dir=r"D:\init_mahdi\dataParsers\data\majles_mj_qa_context",
# batch_size=50000
# )
query1 = {
"_source": ["id", "bab", "group", "sub_group", "book_title", "content"],
"query": {
"bool": {
"must_not": [{"exists": {"field": "embedding"}}],
}
},
}
query = {"query": {"term": {"version_key": "docx_1"}}}
query2 = {"query": {"bool": {"must": [{"match": {"book_title": "نهج البلاغه"}}]}}}
f_data = list(
hit
for hit in scan(
elastic.es,
# index="majles_mj_mashruh",
index="hamyar_bk_section",
query=query2,
size=1000,
)
)
print(f"f_data {len(f_data)}")
DataHelper.save_orjson(
data=f_data,
path=r"D:\init_mahdi\dataParsers\data\hamyar_bk_section_نهج_البلاغه.json",
)
#######################################
# elastic.exportToJsonForAI(
# fields=["embedding"],
# path_back=r"D:\init_mahdi\dataParsers\data",
# index_name="monir_mn_voice_sanad",
# out_name="monir_mn_voice_sanad.json",
# )
# elastic.exportToJsonForAI(
# path_back=r"D:\init_mahdi\dataParsers\data",
# index_name="mn_voice", out_name="mn_voice.json"
# )
#######################################
# python -m app.save_json_from_index
+137
View File
@@ -0,0 +1,137 @@
import os
import uuid
from app.common.data_helper import DataHelper
from pathlib import Path
from dotenv import load_dotenv
from elasticsearch import helpers
from elasticsearch.helpers import scan
from app.common.elastic_helper import ElasticHelper
load_dotenv(dotenv_path=r"D:\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def create_index_mashruh(
elastic: ElasticHelper,
source_index: str = "majles_mj_mashruh",
index_name: str = "majles_mj_mashruh",
batch_size: int = 1000,
) -> int:
"""
رکوردهای ایندکس مبدأ را می‌خواند، id قدیمی را در ref_id نگه می‌دارد،
id جدید می‌سازد و در ایندکس مقصد ذخیره می‌کند.
تعداد کل رکوردهای نوشته‌شده را برمی‌گرداند.
"""
query = {"query": {"bool": {"filter": [{"term": {"version_key": "docx_1"}}]}}}
query2 = {"query": {"bool": {"filter": [{"term": {"version_key": "docx_1_1"}}]}}}
def flush(actions: list) -> int:
if not actions:
return 0
success, _ = helpers.bulk(elastic.es, actions)
return success
actions = []
mapping_ids = {}
total = 0
START = 10_000_000 # اولین عدد ۸ رقمی
counter = START
for hit in scan(elastic.es, index=source_index, query=query, size=batch_size):
doc = hit["_source"]
old_id = doc["id"]
# new_id = f"dx{uuid.uuid4().hex[:8]}"
new_id = f"dx{counter}"
counter += 1
mapping_ids[hit["_id"]] = new_id
doc["ref_id"] = old_id
doc["id"] = new_id
doc["version_key"] = "docx_1_1"
actions.append({"_index": index_name, "_id": doc["id"], "_source": doc})
if len(actions) >= batch_size:
total += flush(actions)
actions = []
total += flush(actions) # باقی‌مانده‌ی آخر
DataHelper.save_orjson(
data=mapping_ids, path=r"D:\dataParsers\data\mapping_ids_mashruh.json"
)
return total
import re
def create_index_group_mashruh(
elastic: ElasticHelper,
mapping_ids_mashruh: Path = Path(r"D:\dataParsers\data\mapping_ids_mashruh.json"),
source_index: str = "majles_group_mashruh",
target_index: str = "majles_group_mashruh",
source_version: str = "docx_1",
target_version: str = "docx_1_1",
batch_size: int = 1000,
) -> int:
"""
کل اسناد (با تمام فیلدها از جمله امبدینگ) را کپی می‌کند،
id و merge_ids را با mapping جدید عوض می‌کند و ورژن را به target_version می‌برد.
"""
mapping = DataHelper.load_orjson(mapping_ids_mashruh)
print(f"mapping_ids_mashruh {len(mapping)}")
query = {"query": {"bool": {"filter": [{"term": {"version_key": source_version}}]}}}
def flush(actions: list) -> int:
if not actions:
return 0
success, _ = helpers.bulk(elastic.es, actions)
return success
actions = []
total = 0
missing = 0
for hit in scan(elastic.es, index=source_index, query=query, size=batch_size):
doc = hit["_source"]
old_id = doc["id"]
m = re.search(r"-(\d+)$", old_id)
if m:
num = m.group(1) # "1"
base = old_id[: m.start()] # "X9hWwKEBp4aoUwS9R-3f"
if base not in mapping:
missing += 1
continue
doc["ref_id"] = old_id
doc["id"] = f"{mapping[base]}-{num}"
doc["merge_ids"] = [mapping[i] for i in doc["merge_ids"] if i in mapping]
doc["version_key"] = target_version
actions.append({"_index": target_index, "_id": doc["id"], "_source": doc})
if len(actions) >= batch_size:
total += flush(actions)
actions = []
total += flush(actions) # باقی‌مانده‌ی آخر
print(f"copied {total}, skipped (no mapping) {missing}")
return total
if __name__ == "__main__":
# count = create_index_mashruh(elastic)
count = create_index_group_mashruh(elastic)
print(f"{count} documents indexed.")
# cd D:\dataParsers\
# python -m app.update_ids_mashruh
+299
View File
@@ -0,0 +1,299 @@
from dotenv import load_dotenv
import os, sys, re
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
from pydantic import BaseModel
from typing import Literal, List, Dict, Any, Optional
from pathlib import Path
from elasticsearch import helpers
from elasticsearch.helpers import scan
load_dotenv(dotenv_path=r"D:\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
print(f"host {host} password {password}")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def creat_index_majles_group_mashruh(
elastic: ElasticHelper,
input_path=Path(r"D:\dataParsers\data\finall_mashruh.json"),
index_name="majles_group_mashruh",
_field="ai_keywords",
version_key="mis4-119b",
batch_size=1000,
):
actions = []
total = 0
success = 0
failed = 0
print("=" * 80)
print("START BULK EMBEDDING UPDATE")
print(f"Index : {index_name}")
print(f"Input path : {input_path}")
print(f"Batch size : {batch_size}")
print("=" * 80)
in_data = DataHelper.load_orjson(input_path)
# in_data = list(input_path.rglob("*.json"))
print(f"in_data {len(in_data)}")
############################################################
query = {
"_source": ["id"],
"query": {
"bool": {
# "filter": [{"term": {"version_key": "base_v3"}}],
"must": [{"exists": {"field": "owl"}}],
}
},
}
process_ids = set()
# hit["_id"]
# for hit in scan(
# elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید
# # index="majles_mj_qa_rule",
# index="majles_mj_qa_context",
# query=query,
# size=1000,
# )
# )
print(f"process_ids {len(process_ids)} => ")
# print(f"process_ids {len(process_ids)} => {list(process_ids)[1]}")
############################################################
for _id, data in in_data.items():
try:
# data = DataHelper.load_orjson(j_path)
doc_id = _id
# embedding = data["embed"]
_data = []
for item in data:
_data.append(
{
"version_key": version_key,
"main_type": item["_key"],
"sub_type": item["type"],
"label": item["keyword"],
}
)
if doc_id in process_ids:
# print(f"doc_id {doc_id}")
continue
# doc_id = re.sub(r"(_v3)(\d+)$", r"\1-\2", data["id"])
# print(f"doc_id {doc_id}")
# return
action = {
"_op_type": "update",
"_index": index_name,
"_id": doc_id,
"doc": {_field: _data},
}
actions.append(action)
total += 1
# Send batch
if len(actions) >= batch_size:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print(
f"processed={total:,} | "
f"success={success:,} | "
f"failed={failed:,}"
)
actions.clear()
except Exception as e:
failed += 1
print(f" {type(e).__name__}: {e}")
# Remaining documents
if actions:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print()
print("=" * 80)
print("BULK UPDATE FINISHED")
print(f"Total : {total:,}")
print(f"Success: {success:,}")
print(f"Failed : {failed:,}")
print("=" * 80)
def creat_index_majles_context_section(
elastic: ElasticHelper,
input_path=Path(r"D:\dataParsers\data\finall_qanon_phase1.json"),
index_name="majles_mj_qa_context",
_field="ai_keywords",
version_key="mis4-119b",
batch_size=1000,
):
actions = []
total = 0
success = 0
failed = 0
print("=" * 80)
print("START BULK EMBEDDING UPDATE")
print(f"Index : {index_name}")
print(f"Input path : {input_path}")
print(f"Batch size : {batch_size}")
print("=" * 80)
in_data = DataHelper.load_orjson(input_path)
# in_data = list(input_path.rglob("*.json"))
print(f"in_data {len(in_data)}")
############################################################
query = {
"_source": ["id"],
"query": {
"bool": {
# "filter": [{"term": {"version_key": "base_v3"}}],
"must": [{"exists": {"field": "owl"}}],
}
},
}
process_ids = set()
# hit["_id"]
# for hit in scan(
# elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید
# # index="majles_mj_qa_rule",
# index="majles_mj_qa_context",
# query=query,
# size=1000,
# )
# )
print(f"process_ids {len(process_ids)} => ")
# print(f"process_ids {len(process_ids)} => {list(process_ids)[1]}")
############################################################
for _id, data in in_data.items():
try:
doc_id = _id
# embedding = data["embed"]
_data = []
for item in data:
_data.append(
{
"version_key": version_key,
"main_type": item["_key"],
"sub_type": item["type"],
"label": item["keyword"],
}
)
if doc_id in process_ids:
# print(f"doc_id {doc_id}")
continue
action = {
"_op_type": "update",
"_index": index_name,
"_id": doc_id,
"doc": {_field: _data},
}
actions.append(action)
total += 1
# Send batch
if len(actions) >= batch_size:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print(
f"processed={total:,} | "
f"success={success:,} | "
f"failed={failed:,}"
)
actions.clear()
except Exception as e:
failed += 1
print(f" {type(e).__name__}: {e}")
# Remaining documents
if actions:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print()
print("=" * 80)
print("BULK UPDATE FINISHED")
print(f"Total : {total:,}")
print(f"Success: {success:,}")
print(f"Failed : {failed:,}")
print("=" * 80)
# creat_index_majles_group_mashruh(elastic=elastic)
creat_index_majles_context_section(elastic=elastic)
# cd D:\dataParsers\
# python -m app.update_keywords
+165
View File
@@ -0,0 +1,165 @@
from dotenv import load_dotenv
import os, sys, re
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
from pydantic import BaseModel
from typing import Literal, List, Dict, Any, Optional
from pathlib import Path
from elasticsearch import helpers
from elasticsearch.helpers import scan
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
print(f"host {host} password {password}")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def creat_index(
elastic: ElasticHelper,
input_path=Path(
r"D:\init_mahdi\dataParsers\data\hamyar_bk_section_step2\finall_data"
# r"D:\init_mahdi\dataParsers\data\data_context\output_dir"
# r"D:\init_mahdi\dataParsers\data\hamyar_bk_section\finall_data.json"
# r"D:\init_mahdi\dataParsers\data\output_dir"
# r"D:\init_mahdi\dataParsers\data\jinav5_rule_v3_p1_embed\embedings"
),
index_name="hamyar_bk_section",
batch_size=1000,
):
"""
Update existing Elasticsearch documents with embeddings.
Each JSON file must contain:
{
"id": "...",
"emb": [...]
}
The document with the corresponding _id must already exist in Elasticsearch.
"""
actions = []
total = 0
success = 0
failed = 0
print("=" * 80)
print("START BULK EMBEDDING UPDATE")
print(f"Index : {index_name}")
print(f"Input path : {input_path}")
print(f"Batch size : {batch_size}")
print("=" * 80)
# in_data = list(input_path.rglob("*.json"))
# print(f"in_data {len(in_data)}")
############################################################
query = {
"_source": ["id"],
"query": {
"bool": {
# "filter": [{"term": {"version_key": "base_v3"}}],
"must": [{"exists": {"field": "embedding"}}],
}
},
}
# process_ids = set(
# hit["_id"]
# for hit in scan(
# elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید
# index=index_name,
# query=query,
# size=1000,
# )
# )
process_ids = set()
print(f"process_ids {len(process_ids)} ")
############################################################
# for data in DataHelper.load_orjson(input_path):
for j_path in input_path.rglob("*.json"):
for data in DataHelper.load_orjson(j_path):
try:
# data = DataHelper.load_orjson(j_path)
doc_id = data["id"]
embedding = data["embed"]
if doc_id in process_ids:
# print(f"doc_id {doc_id}")
continue
# doc_id = re.sub(r"(_v3)(\d+)$", r"\1-\2", data["id"])
# print(f"doc_id {doc_id}")
# return
action = {
"_op_type": "update",
"_index": index_name,
"_id": doc_id,
"doc": {"embedding": embedding},
}
actions.append(action)
total += 1
# Send batch
if len(actions) >= batch_size:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print(
f"processed={total:,} | "
f"success={success:,} | "
f"failed={failed:,}"
)
actions.clear()
except Exception as e:
failed += 1
print(f"[ERROR] {input_path}")
print(f" {type(e).__name__}: {e}")
# Remaining documents
if actions:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print()
print("=" * 80)
print("BULK UPDATE FINISHED")
print(f"Total : {total:,}")
print(f"Success: {success:,}")
print(f"Failed : {failed:,}")
print("=" * 80)
creat_index(elastic=elastic)
# python -m app.update_mj_qa_rules_embedding
+104
View File
@@ -0,0 +1,104 @@
from pydantic import BaseModel
from typing import List, Dict
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
from pydantic import BaseModel
from typing import List
from pathlib import Path
class NewArch(BaseModel):
id: str
ref_id: str
ref_key: str
begin_date: str
begin_year: int
author: str
branch: str
title: str
content: str
meet_no: int
permit_tags: str
format: str
embedding: List
host = "http://192.168.23.99:6900"
password = "5T6xbblcix3GdCGnYEk6"
print(f"host {host} password {password}")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def do_convert(
elastic,
embed_json_path=Path(r"D:\init_mahdi\dataParsers\data\monir_mn_voice_sanad"),
dest_index_name="monir_mn_voice_sanad",
bulk_size=200,
):
map_mn_sanad = {
i["_id"]: i["_source"]
for i in DataHelper.load_orjson(r"D:\init_mahdi\dataParsers\data\mn_sanad.json")
}
map_mn_voice = {
i["_id"]: i["_source"]
for i in DataHelper.load_orjson(r"D:\init_mahdi\dataParsers\data\mn_voice.json")
}
bulk_list = []
f_counter = 0
total = 0
for j_path in embed_json_path.rglob("*.json"):
j_data = DataHelper.load_orjson(j_path)
total += len(j_data)
for data in j_data:
data = data["_source"]
index_key = data["index_key"]
mom_id = data["mom_id"]
# if index_key == "mn_voice":
# elif index_key == "mn_sanad":
try:
metadata = map_mn_sanad[mom_id]
except:
metadata = map_mn_voice[mom_id]
metadata["permit_tags"] = ""
metadata["begin_date"] = metadata["begin_date"]
if len(metadata["begin_date"]) > 0:
metadata["begin_year"] = int(metadata["begin_date"].split("-")[0])
else:
metadata["begin_year"] = 0
# "begin_date": "2013-11-05T00:00:00",
new_data = NewArch(
id=data["id"],
ref_key=index_key,
ref_id=mom_id,
author=metadata["author"],
branch=metadata["branch"],
title=metadata["title"],
content=data["content"],
meet_no=metadata["meet_no"],
permit_tags=metadata["permit_tags"],
format=metadata["format"],
begin_date=metadata["begin_date"],
begin_year=metadata["begin_year"],
embedding=data["embedding"],
)
bulk_list.append({"_id": new_data.id, "_source": new_data.model_dump()})
if len(bulk_list) >= bulk_size:
f_counter += len(bulk_list)
elastic.importBulkList(listData=bulk_list, index_name=dest_index_name)
bulk_list = []
print(f"--- {f_counter}/{total} ---")
if len(bulk_list) > 0:
f_counter += len(bulk_list)
elastic.importBulkList(listData=bulk_list, index_name=dest_index_name)
bulk_list = []
print(f"--- {f_counter}/{total} ---")
do_convert(elastic=elastic)
# cd dataParsers
# python -m app.update_monir_mn_voice_sanad