first commit

This commit is contained in:
init_mahdi
2026-11-23 20:06:18 +03:30
parent 179d37336b
commit 69d8af4b18
17 changed files with 2185 additions and 27 deletions
+6
View File
@@ -51,3 +51,9 @@ mj_qa_section.json
rerank_data.json
test1.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
+278 -17
View File
@@ -4,6 +4,8 @@ import os
import json
from time import sleep
from elasticsearch import Elasticsearch, helpers
from pathlib import Path
import orjson
class ElasticHelper:
@@ -91,7 +93,6 @@ class ElasticHelper:
res = self.es.exists(index=index_name, id=id)
return res
def update_index_doc(self, is_update_state, index_name_o, eid, data):
"""
نوع ورودی:
@@ -135,6 +136,7 @@ class ElasticHelper:
fields=[],
mode="normal",
collapse_field="",
size=1000,
):
print("*" * 50, " start backup -->", index_name)
self.counter = 0
@@ -144,7 +146,7 @@ class ElasticHelper:
if out_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"]
print("start index = %s" % index_name)
@@ -270,7 +272,7 @@ class ElasticHelper:
if body == {}:
s_res = self.es.search(index=index_name, scroll="5m", size=1000)
else:
if not "size" in body :
if not "size" in body:
body["size"] = 1000
s_res = self.es.search(index=index_name, scroll="5m", body=body)
self.total = s_res["hits"]["total"]["value"]
@@ -349,7 +351,13 @@ class ElasticHelper:
# - داده‌ها را از فایل ZIP به Elasticsearch بازیابی می‌کند
# -----------------------------end----------------------------
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):
print(" **** error *** path not exist: ", path_back)
@@ -369,7 +377,13 @@ class ElasticHelper:
self.zipFileToElastic(file_path, index_name)
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):
print(" **** error *** path not exist: ", path_file)
@@ -526,9 +540,9 @@ class ElasticHelper:
# - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند
# - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود
# -----------------------------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_mapping1 = path_base + "general/"
if app_key == "":
@@ -599,7 +613,7 @@ class ElasticHelper:
}
)
if streem_state :
if streem_state:
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
@@ -610,7 +624,7 @@ class ElasticHelper:
if not ok:
print("Error:", result)
else :
else:
helpers.bulk(
self.es,
actions,
@@ -638,7 +652,7 @@ class ElasticHelper:
stats_only = True
yield_ok = False
actions=[]
actions = []
for item in listData:
actions.append(
{
@@ -649,7 +663,7 @@ class ElasticHelper:
}
)
if streem_state :
if streem_state:
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
@@ -660,7 +674,7 @@ class ElasticHelper:
if not ok:
print("Error:", result)
else :
else:
helpers.bulk(
self.es,
actions,
@@ -681,7 +695,9 @@ class ElasticHelper:
# - داده‌ها را به صورت bulk وارد می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def importJsonDataToElastic(self, jsonData, index_name, fields=[], streem_state = False):
def importJsonDataToElastic(
self, jsonData, index_name, fields=[], streem_state=False
):
chunk_size = 100000
raise_on_error = False
raise_on_exception = False
@@ -707,7 +723,7 @@ class ElasticHelper:
"_source": source,
}
)
if streem_state :
if streem_state:
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
@@ -718,7 +734,7 @@ class ElasticHelper:
if not ok:
print("Error:", result)
else :
else:
success, errors = helpers.bulk(
self.es,
actions,
@@ -730,7 +746,6 @@ class ElasticHelper:
)
return success, errors
# ----------------------------start---------------------------
# متد fileToElastic:
# نوع ورودی:
@@ -899,7 +914,7 @@ class ElasticHelper:
scroll=scroll_timeout,
**kwargs,
size=pagesize,
body=body
body=body,
)
else:
result = self.es.search(
@@ -1176,3 +1191,249 @@ class ElasticHelper:
except Exception as e:
print(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,
}
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
+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