monir , majles update2

This commit is contained in:
hsafaei
2025-12-09 19:55:37 +03:30
parent 9bb61a60b2
commit f4e8832e61
13 changed files with 1492 additions and 222 deletions
+115
View File
@@ -2,6 +2,9 @@ import pickle
import re import re
import string import string
import os import os
import pickle, os, orjson, string, re, openpyxl
from pathlib import Path
from bs4 import BeautifulSoup
class DataHelper(): class DataHelper():
@@ -150,3 +153,115 @@ class DataHelper():
verb_tense_map = [verb_p2f_map, verb_f2p_map] verb_tense_map = [verb_p2f_map, verb_f2p_map]
return lexicon_stem, verb_stem, verb_tense_map, irregular_noun return lexicon_stem, verb_stem, verb_tense_map, irregular_noun
@staticmethod
def save_orjson(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)
)
@staticmethod
def load_orjson(path: str | Path):
"""
تابع برای بارگزاری جیسون با نهایت سرعت
path: آدرس کامل فایل ورودی
"""
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
@staticmethod
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(u'\xa0', ' ').strip()
return text
@staticmethod
def json_to_excel(data, output_path="output.xlsx"):
"""
data: list of dict
output_path: path to save excel file
"""
if not data:
raise ValueError("JSON data is empty.")
# ساختن فایل اکسل
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Sheet1"
# ستون‌ها
headers = list(data[0].keys())
ws.append(headers)
# ردیف‌ها
for item in data:
row = [item.get(h, "") for h in headers]
ws.append(row)
wb.save(output_path)
return output_path
@staticmethod
def count_tokens(model_name, system_prompt, user_prompt):
"""
شمارش دقیق توکن‌های ورودی برای مدل‌های مختلف
"""
text = f"<|system|>\n{system_prompt}\n<|user|>\n{user_prompt}"
# --- انتخاب tokenizer ---
if "openai" in model_name.lower() or "gpt" in model_name.lower():
import tiktoken
# مدل‌های مشابه GPT یا OSS از tiktoken استفاده می‌کنند
enc = tiktoken.get_encoding("cl100k_base")
tokens = enc.encode(text)
return len(tokens)
elif "gemma" in model_name.lower():
from transformers import AutoTokenizer
# SentencePiece tokenizer (Gemma از HuggingFace)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokens = tokenizer.encode(text)
return len(tokens)
elif "magistral" in model_name.lower() or "mistral" in model_name.lower():
from transformers import AutoTokenizer
# Mistral / Magistral tokenizer (BPE)
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
tokens = tokenizer.encode(text)
return len(tokens)
else:
raise ValueError(f"Model {model_name} not recognized.")
+2 -1
View File
@@ -526,8 +526,9 @@ class ElasticHelper:
# - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند # - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند
# - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود # - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود
# -----------------------------end---------------------------- # -----------------------------end----------------------------
def createIndex(self, index_name, app_key="", map_name=""): def createIndex(self, index_name, app_key="", map_name="", 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 == "":
+6 -1
View File
@@ -1228,6 +1228,11 @@ def convert_persian_date(value):
if _date != _date : # True اگر NaN باشد: if _date != _date : # True اگر NaN باشد:
return res, '' return res, ''
_date = str(_date)
if _date :
_date = _date.replace('-', '/')
_date = _date.replace('\\', '/').strip()
if _date and not is_match_persian_date_format(_date): if _date and not is_match_persian_date_format(_date):
return res, "error match_persian_date_format" return res, "error match_persian_date_format"
@@ -1246,7 +1251,7 @@ def repair_object_persian_date(item, key, error_list=None, id='', key2=''):
res, error = convert_persian_date(_date) res, error = convert_persian_date(_date)
if not res : if not res :
if not error_list is None : if error and not error_list is None :
error_list.append({'id':id, 'key': path_key, "value":_date, "message": error }) error_list.append({'id':id, 'key': path_key, "value":_date, "message": error })
del item[key] del item[key]
return item return item
+67
View File
@@ -0,0 +1,67 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import zipfile
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.for_ai.codes_import_from_excel import (
run_codes_extract_directory,
run_codes_to_elastic_directory,
)
from app.parvande_qanon.import_qavanin_excels_to_elastic import (
import_excel_before_to_elastic,
import_excel_after_to_elastic,
import_excel_tasmimat_to_elastic,
)
from app.parvande_qanon.repair_qa_qanon_for_map_new import *
text_normal = TextNormalizer()
load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
# print( "---------------->>>>>>>>>>>>>>>", host )
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
print(".... majles_codes_update_steps ......", 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
col_index = {
"row_number": 0,
"section_title": 1,
"ts_date": 2,
"qanon_title": 3,
"code_state": 4,
"code_label": 5,
"qanon_id": 6,
"section_id": 7,
"state_match": 8,
}
# run_codes_to_elastic_directory( elastic, "./data/tcodes/corrected_majles/not_edit2", "./data/tcodes/corrected_majles/not_edit2/result", all_codes, False, True, col_index, False)
# run_codes_extract_directory("./data/tcodes/corrected_majles/not_edit2/result","./data/tcodes/corrected_majles/not_edit2/result_json",all_codes,col_index,True)
@@ -44,91 +44,7 @@ path_base_map = "G:/Project2/gateway_php/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map) elastic = ElasticHelper(host, password, "elastic", path_base_map)
# ------------------------------------- # -------------------------------------
# --- مواردی از قانونهای جدید که فیلد زیر را ندارند باید اصلاح شوند # ----- یک بار فقط
# --- main_type
# POST mj_qa_qanon/_update_by_query
body = {
"query": {"bool": {"must_not": [{"exists": {"field": "main_type"}}]}},
"script": {
"source": """
ctx._source.main_type = 'قانون'
""",
"lang": "painless",
},
}
# elastic.updateByQueryIndex("mj_qa_qanon", body)
# POST mj_qa_qanon/_update_by_query
body = {
"query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
"script": {
"source": """
ctx._source.sub_type = ctx._source.main_type;
ctx._source.main_type = 'قانون'
""",
"lang": "painless",
},
}
# elastic.updateByQueryIndex("mj_qa_qanon", body)
# PUT mj_df_qanon/_mapping
# {
# "properties":{
# "mom_type": {
# "type": "keyword"
# },
# "main_type_key": {
# "type": "keyword"
# }
# }
# }
# POST mj_df_qanon/_update_by_query
body = {
"query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
"script": {
"source": """
ctx._source.mom_type = ctx._source.main_type;
ctx._source.main_type = 'قانون';
ctx._source.main_type_key = 'qasection';
""",
"lang": "painless",
},
}
# elastic.updateByQueryIndex("mj_df_qanon", body)
# -------------------------------------
# ------ استخراج برخی کدهای باقیمانده که اکسل آنها از قبل موجود هست و تولید فایل مناسب برای درج فایل محور در بانک مجلس
# ---
all_codes = []
with open("./data/codes49.json", "r", encoding="utf8") as f:
codes_1 = json.load(f)
all_codes = codes_1
col_index = {
"row_number": 0,
"section_title": 1,
"ts_date": 2,
"qanon_title": 3,
"code_state": 4,
"code_label": 5,
"qanon_id": 6,
"section_id": 7,
"state_match": 8,
}
run_codes_to_elastic_directory( elastic, "./data/tcodes/corrected_majles/not_edit2", "./data/tcodes/corrected_majles/not_edit2/result", all_codes, False, True, col_index, False)
run_codes_extract_directory("./data/tcodes/corrected_majles/not_edit2/result","./data/tcodes/corrected_majles/not_edit2/result_json",all_codes,col_index,True)
# -------------------------------------
# ----- پشتیبان گیری از داده های جدید داتیک # ----- پشتیبان گیری از داده های جدید داتیک
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_rg_section_temp", "mj_rg_section_doctic_14040824") # elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_rg_section_temp", "mj_rg_section_doctic_14040824")
@@ -136,110 +52,197 @@ run_codes_extract_directory("./data/tcodes/corrected_majles/not_edit2/result",".
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_opinion_temp", "mj_qa_opinion_doctic_14040824") # elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_opinion_temp", "mj_qa_opinion_doctic_14040824")
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon_temp", "mj_qa_qanon_doctic_14040824") # elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon_temp", "mj_qa_qanon_doctic_14040824")
# -------------------------------------
# ----- ترمیم داده های تاریخ ایندکس قبلی
# -- qaqanon
file_path = "G:/Project2/160_dotic/mj_qa_qanon_112.zip" # ------------------------------------------ 1 ---------------------------------------------------------------------
# ###### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
# ---------------------------------------------------------------------------------------------------------------
# -------------------------------------
# ----- mj_qa_qanon
# ----- حذف فیزیکی mj_qa_qanon
#DELETE mj_qa_qanon
file_path = "G:/Project2/160_dotic/majles_14040918/mj_qa_qanon.zip"
index_name = "mj_qa_qanon" index_name = "mj_qa_qanon"
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon') #elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon', path_base_map+ 'majles/'+'mj_qa_qanon_new.json' )
###### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
#restore_correct_date_to_elastic(elastic, file_path, index_name, "G:/Project2/160_dotic/date_log_error_qaqanon.txt" ) #restore_correct_date_to_elastic(elastic, file_path, index_name, "G:/Project2/160_dotic/date_log_error_qaqanon.txt" )
# ------------------------------------- # -------------------------------------
# ----- mj_df_qanon
# ----- حذف فیزیکی mj_df_qanon
#DELETE mj_df_qanon
file_path = "G:/Project2/160_dotic/majles_14040918/mj_df_qanon.zip"
index_name = "mj_df_qanon"
# elastic.createIndex( 'mj_df_qanon', 'majles', 'mj_df_qanon', path_base_map+ 'majles/'+'mj_df_qanon_new.json' )
# restore_correct_date_to_elastic(elastic, file_path, index_name, "G:/Project2/160_dotic/date_log_error_dfqanon.txt" )
# ------------------------------------- # -------------------------------------
# ----- mj_qa_section
#### ------>> expire_date, ts_date, ref_state.qanon_date, ref_state.effect_date
# ----- حذف فیزیکی mj_qa_section
#DELETE mj_qa_section
file_path = "G:/Project2/160_dotic/majles_14040918/mj_qa_section.zip"
index_name = "mj_qa_section"
# elastic.createIndex( 'mj_qa_section', 'majles', 'mj_qa_section', path_base_map+ 'majles/'+'mj_qa_section_new.json' )
# restore_correct_date_to_elastic(elastic, file_path, index_name, "G:/Project2/160_dotic/date_log_error_qasection.txt" )
# -------------------------------------
# ----- mj_rg_section
file_path = "G:/Project2/160_dotic/mj_rg_section_doctic_14040824.zip"
# elastic.createIndex( 'mj_rg_section', 'majles', 'mj_rg_section', path_base_map+ 'majles/'+'mj_qa_section_new.json')
# restore_correct_date_to_elastic(elastic, file_path, "mj_rg_section", "G:/Project2/160_dotic/date_log_error_rgsection.txt" )
# --------------------------------------------- 1 ------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------------
# --- مواردی از قانونهای جدید که فیلد زیر را ندارند باید اصلاح شوند
# --- main_type
# # POST mj_qa_qanon/_update_by_query
# body = {
# "query": {"bool": {"must_not": [{"exists": {"field": "main_type"}}]}},
# "script": {
# "source": """
# ctx._source.main_type = 'قانون'
# """,
# "lang": "painless",
# },
# }
# elastic.updateByQueryIndex("mj_qa_qanon", body)
# # POST mj_qa_qanon/_update_by_query
# body = {
# "query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
# "script": {
# "source": """
# ctx._source.sub_type = ctx._source.main_type;
# ctx._source.main_type = 'قانون'
# """,
# "lang": "painless",
# },
# }
# elastic.updateByQueryIndex("mj_qa_qanon", body)
# #----------------------------------------------
# #---- در مپ إعمال شد و نیاز نیست دیگه
# # PUT mj_df_qanon/_mapping
# # {
# # "properties":{
# # "mom_type": {
# # "type": "keyword"
# # },
# # "main_type_key": {
# # "type": "keyword"
# # }
# # }
# # }
# #----------------------------------------------
# # POST mj_df_qanon/_update_by_query
# body = {
# "query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
# "script": {
# "source": """
# ctx._source.mom_type = ctx._source.main_type;
# ctx._source.main_type = 'قانون';
# ctx._source.main_type_key = 'qasection';
# """,
# "lang": "painless",
# },
# }
# elastic.updateByQueryIndex("mj_df_qanon", body)
# --------------------------------------------- 3 ------------------------------------------------------------------
# --- درج داده های جدید مقررات و آراء در فهرست همه
# ---------------------------------------------------------------------------------------------------------------
# --- موقت
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_1_date")
# -- حذف مقرره های قبلی # -- حذف مقرره های قبلی
body = {"query": {"term": {"main_type": {"value": "مقرره"}}}} body = {"query": {"term": {"main_type": {"value": "مقرره"}}}}
# elastic.deleteByQueryIndex("mj_qa_qanon", body) # elastic.deleteByQueryIndex("mj_qa_qanon", body)
# --- موقت
#elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_2_base")
# ------------------------------------- # -------------------------------------
# ----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base")
# ------------------------------------- # -------------------------------------
# --- درج داده های جدید مقرره
# import_data_new_qaqanon(elastic, "G:/Project2/160_dotic/mj_qa_qanon_doctic_14040824.zip") # import_data_new_qaqanon(elastic, "G:/Project2/160_dotic/mj_qa_qanon_doctic_14040824.zip")
# ----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base_dotic")
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base_dotic.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# ------------------------------------- # ----- انتقال داده های آراء به
# ------------------------------------- #### بخاطر لزوم تغییر روش کار، لازم شد محتوای آراء به اینجا منتفل شود
# ------------------------------------- #### البته بقیه فراداده قبلا منتقل شده بودند
# file_path = 'G:/Project2/160_dotic/mj_qa_opinion_doctic_14040824.zip'
# index_name = "mj_qa_qanon"
# import_content_opinion_to_qaqanon(elastic, file_path, index_name )
# --- موقت
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_3_base_dotic")
# --------------------------------------------- 4 ------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------------
file_before = "G:/Project2/160_dotic/duplicate_before.json" file_before = "G:/Project2/160_dotic/duplicate_before.json"
file_after = "G:/Project2/160_dotic/duplicate_after.json" file_after = "G:/Project2/160_dotic/duplicate_after.json"
file_tasmim = "G:/Project2/160_dotic/duplicate_tasmim.json" file_tasmim = "G:/Project2/160_dotic/duplicate_tasmim.json"
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon', path_base_map+ 'majles/'+'mj_qa_qanon_new.json' )
# #------------------------------------------ # elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_3_base_dotic.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# duplicate_list = {}
# file_excel = r"G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# with open(file_before, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# # #------------------------------------------ # # #------------------------------------------
duplicate_list = {}
file_excel = r"G:\Project2\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
with open(file_before, 'w', encoding='utf8') as f :
json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# # # #------------------------------------------
# duplicate_list = {} # duplicate_list = {}
# with open(file_before, 'r', encoding='utf8') as f : # with open(file_before, 'r', encoding='utf8') as f :
# duplicate_list = json.loads( f.read()) # duplicate_list = json.loads( f.read())
# file_excel = r"G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx" # file_excel = r"G:\Project2\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_after_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list) # import_excel_after_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# with open(file_after, 'w', encoding='utf8') as f : # with open(file_after, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4) # json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# # #------------------------------------------ # # # #------------------------------------------
# duplicate_list = {} # duplicate_list = {}
# with open(file_after, 'r', encoding='utf8') as f : # with open(file_after, 'r', encoding='utf8') as f :
# duplicate_list = json.loads( f.read()) # duplicate_list = json.loads( f.read())
# file_excel = r"G:\Project2\NLP\dataParsers\data\qavanin_files\فهرست تصمیمات قانونی.xlsx" # file_excel = r"G:\Project2\dataParsers\data\qavanin_files\فهرست تصمیمات قانونی.xlsx"
# import_excel_tasmimat_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list) # import_excel_tasmimat_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# with open(file_tasmim, 'w', encoding='utf8') as f : # with open(file_tasmim, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4) # json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# ----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ... # # --- موقت
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base_excel") # elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_4_base_excel")
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base_excel.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# -------------------------------------
# ----- انتقال داده های آراء به
# -- qaqanon
# file_path = 'G:/Project2/160_dotic/mj_qa_opinion_doctic_14040824.zip'
# index_name = "mj_qa_qanon"
#### بخاطر لزوم تغییر روش کار، لازم شد محتوای آراء به اینجا منتفل شود
#### البته بقیه فراداده قبلا منتقل شده بودند
# import_content_opinion_to_qaqanon(elastic, file_path, index_name )
# -------------------------------------
# ---- اصلاح تاریخهای اجزاء طبق ساختار جدید date
# -- qasection
#### ------>> expire_date, ts_date, ref_state.qanon_date, ref_state.effect_date
file_path = "G:/Project2/160_dotic/mj_qa_section_doctic_14040824.zip"
# elastic.createIndex( 'mj_qa_section', 'majles', 'mj_qa_section')
###### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
# restore_correct_date_to_elastic(elastic, file_path, "mj_qa_section", "G:/Project2/160_dotic/date_log_error_qasection.txt" )
# ---- اصلاح تاریخهای اجزاء طبق ساختار جدید date
# -- rgsection
file_path = "G:/Project2/160_dotic/mj_rg_section_doctic_14040824.zip"
# elastic.createIndex( 'mj_rg_section', 'majles', 'mj_rg_section')
##### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
# restore_correct_date_to_elastic(elastic, file_path, "mj_rg_section", "G:/Project2/160_dotic/date_log_error_rgsection.txt" )
# ..... # .....
@@ -251,7 +254,15 @@ file_path = "G:/Project2/160_dotic/mj_rg_section_doctic_14040824.zip"
# ------------------------------------ # ------------------------------------
# ------------------------------------ # ------------------------------------
#--- mj_qa_section ???
# بررسی پر بودن main_type مجلس برای نوع اصلی/تبعی/مهذب # بررسی پر بودن main_type مجلس برای نوع اصلی/تبعی/مهذب
# و تغییر به mom_type # و تغییر به mom_type
# schema ???
# 'key' => 'mom_type', # 'key' => 'mom_type',
# 'label' => 'نوع اصلی/تبعی/مهذب', # 'label' => 'نوع اصلی/تبعی/مهذب',
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base_excel.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
+8 -8
View File
@@ -66,8 +66,8 @@ class MnSection(BaseModel):
main_type: str main_type: str
html: str html: str
content: str content: str
meet_info: Properties meet_info: dict
term_info: Properties term_info: dict
tree_info: TreeInfo tree_info: TreeInfo
content_len: int content_len: int
word_len: int word_len: int
@@ -108,8 +108,8 @@ class MnMeetEntity(BaseModel):
time_create: int time_create: int
time_edit: int time_edit: int
file_links: FileLinks file_links: FileLinks
meet_info: Properties meet_info: dict
term_info: Properties term_info: Optional[dict] = None
class Subjects(BaseModel): class Subjects(BaseModel):
@@ -139,7 +139,7 @@ class MnMeet(BaseModel):
title: str title: str
meet_no: int meet_no: int
author: str author: str
term_info: Optional[Properties] = Field("", description="کلید اتصال به جدول ترم") term_info: dict | None = None
subtitle: str subtitle: str
subjects: Optional[List[Subjects]] = [] subjects: Optional[List[Subjects]] = []
allwords: str allwords: str
@@ -212,9 +212,9 @@ class MNSection(BaseModel):
id : str id : str
html : str html : str
content : str content : str
meet_info: Properties meet_info: dict
term_info: Properties term_info: Optional[dict] = None
tree_info: TreeProperties tree_info: dict
content_len: int content_len: int
word_len: int word_len: int
tags: str tags: str
+595
View File
@@ -0,0 +1,595 @@
import re
from typing import Dict, Optional
from typing import List, Tuple
from typing import ClassVar
from typing import ClassVar, Optional, Set, FrozenSet
class TextNormalizer:
HAMZE_PATTERN: List[Tuple[re.Pattern[str], str]] = [
(re.compile(r"ئ|ﺌ|ﺋ"), "ی"),
(re.compile(r"ؤ|ﺅ"), "و"),
(re.compile(r"ﺔ|ۀ|ﺓ|ة"), "ه"),
(re.compile(r"إ|أ"), "ا"),
]
CHAR_PATTERN_MONIR: List[Tuple[re.Pattern[str], str]] = [
(re.compile(r"\u200e|\u200f"), " "), # LTR, RTL
(re.compile(r"\u00AD|\u00AC"), "\u200c"), # نیم اسپیس خاص
(re.compile(r"(\u002C)+"), "\u200c"), # نیم اسپیس تکراری
(re.compile(r"ﺁ|آ"), "آ"),
(re.compile(r"ﺎ|ٱ|ﺍ"), "ا"),
(re.compile(r"ٲ|أ|ﺄ|ﺃ"), "أ"),
(re.compile(r"ﺈ|ٳ|ﺇ"), "إ"),
(re.compile(r"ﺐ|ﺏ|ﺑ|ٮ|ﺒ"), "ب"),
(re.compile(r"ﭖ|ﭗ|ﭙ|ﭘ|ݒ|ݐ"), "پ"),
(re.compile(r"ﭡ|ٺ|ٹ|ﭞ|ٿ|ټ|ﺕ|ﺗ|ﺖ|ݓ|ﺘ"), "ت"),
(re.compile(r"ﺙ|ﺛ|ﺚ|ݑ|ݖ|ﺜ"), "ث"),
(re.compile(r"ﺝ|ڃ|ﺠ|ﺟ|ڄ"), "ج"),
(re.compile(r"ڃ|ﭽ|ݘ|ﭻ|ﭼ"), "چ"),
(re.compile(r"ﺢ|ﺤ|څ|ځ|ﺣ"), "ح"),
(re.compile(r"ﺥ|ﺦ|ﺨ|ﺧ"), "خ"),
(re.compile(r"ڏ|ډ|ﺪ|ڌ|ﺩ"), "د"),
(re.compile(r"ﺫ|ﺬ|ذ"), "ذ"),
(re.compile(r"ڙ|ڗ|ڒ|ڑ|ڕ|ﺭ|ړ|ڔ|ݫ|ݬ|ﺮ"), "ر"),
(re.compile(r"ﺰ|ﺯ"), "ز"),
(re.compile(r"ﮋ|ﮊ|ࢲ"), "ژ"),
(re.compile(r"ݭ|ݜ|ﺱ|ﺲ|ښ|ﺴ|ﺳ"), "س"),
(re.compile(r"ﺵ|ﺶ|ﺸ|ﺷ"), "ش"),
(re.compile(r"ﺺ|ﺼ|ﺻ|ﺹ"), "ص"),
(re.compile(r"ﺽ|ﺾ|ﺿ|ﻀ"), "ض"),
(re.compile(r"ﻁ|ﻂ|ﻃ|ڟ|ﻄ"), "ط"),
(re.compile(r"ﻆ|ﻇ|ﻈ"), "ظ"),
(re.compile(r"ڠ|ﻉ|ﻊ|ﻋ|ﻌ"), "ع"),
(re.compile(r"ﻎ|ۼ|ﻍ|ﻐ|ﻏ"), "غ"),
(re.compile(r"ﻒ|ڤ|ﻑ|ﻔ|ڡ|ݠ|ݡ|ﻓ"), "ف"),
(re.compile(r"ﻕ|ﻖ|ﻗ|ڨ|ﻘ|ٯ"), "ق"),
(re.compile(r"ڭ|ﻚ|ﮎ|ﻜ|ﮏ|ګ|ﻛ|ﮑ|ﮐ|ڪ|ݢ|ݣ|ݤ|ك|ࢴ"), "ک"),
(re.compile(r"ﮚ|ﮒ|ﮓ|ﮕ|ڳ|ﮔ"), "گ"),
(re.compile(r"ﻝ|ﻞ|ﻠ|ڵ|ﻟ"), "ل"),
(re.compile(r"ﻵ|ﻶ|ﻷ|ﻸ|ﻹ|ﻺ|ﻻ|ﻼ"), "لا"),
(re.compile(r"ﻡ|ﻤ|ﻢ|ݥ|ݦ|ﻣ"), "م"),
(re.compile(r"ڼ|ﻦ|ﻥ|ﻨ|ݔ|ݧ|ݨ|ݩ|ݪ|ﻧ"), "ن"),
(re.compile(r"ވ|ﯙ|ۈ|ۋ|ﺆ|ۊ|ۇ|ۏ|ۅ|ۉ|ﻭ|ﻮ|ٶ|ۆ|ؤ"), "و"),
(re.compile(r"ﻬ|ھ|ﻩ|ﻫ|ﻪ|ە|ۂ|ۃ|٥|ﮪ|ﮬ|ﮭ|ہ"), "ه"),
(re.compile(r"ﭛ|ﻯ|ۍ|ﻰ|ﻱ|ﻲ|ں|ﻳ|ﻴ|ﯼ|ې|ﯽ|ﯾ|ﯿ|ێ|ے|ى|ي"), "ی"),
(re.compile(r"¬"), "‌"),
(re.compile(r"•|·|●|·|・|∙|。|ⴰ"), "."),
(re.compile(r",|٬|٫|‚|،"), "،"),
(re.compile(r"ʕ"), "؟"),
(re.compile(r"”|“|¨|″"), '"'),
(re.compile(r"۰|٠"), "0"),
(re.compile(r"۱|١"), "1"),
(re.compile(r"۲|٢"), "2"),
(re.compile(r"۳|٣|³"), "3"),
(re.compile(r"۴|٤"), "4"),
(re.compile(r"۵"), "5"),
(re.compile(r"۶|٦"), "6"),
(re.compile(r"۷|٧"), "7"),
(re.compile(r"۸|٨"), "8"),
(re.compile(r"۹|٩"), "9"),
(re.compile(r"²"), "2"),
(re.compile(r"٪"), '%'),
(re.compile(r"ˆ"), '^'),
(re.compile(r"˜"), '~'),
(re.compile(r"٭"), '*'),
(re.compile(r"ᆖ"), '='),
(re.compile(r"‑|–|—|−"), '-'),
(re.compile(r"‹"), '<'),
(re.compile(r"›"), '>'),
# اعراب و تنوین + Maddah
# ً (Fathatan) → U+064B
# ٌ (Dammatan) → U+064C
# ٍ (Kasratan) → U+064D
# َ (Fatha) → U+064E
# ُ (Damma) → U+064F
# ِ (Kasra) → U+0650
# ّ (Shadda) → U+0651
# ْ (Sukun) → U+0652
# ٰ (Maddah above) → U+0670
# (re.compile(r"|ِ|ُ|َ|ٍ|ٌ|ً|"), ""),
# (
# re.compile(r"ـ"),
# "",
# ), # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
]
EMPTY_LINE_PATTERN: List[Tuple[re.Pattern[str], str]] = [
(re.compile(r"\\n"), "\n"),
(re.compile(r"\\r"), "\n"),
(re.compile(r"(\r\n)+"), "\n"),
(re.compile(r"\r+"), "\n"),
(re.compile(r"\f"), "\n"),
]
FINALL_LINE_PATTERN: List[Tuple[re.Pattern[str], str]] = [
# حذف خطوطی که با ":" شروع می‌شوند (حتی با فاصله پیش از آن)
(re.compile(r"^[ \t]*:[^\n]*\n?", re.MULTILINE), ""),
# جایگزینی فواصل اضافی و خطوط خالی (همان قبلی)
(re.compile(r" +"), " "),
(re.compile(r"\n{2,}"), "\n\n"), # حداکثر یک خط خالی بین پاراگراف‌ها
]
# ✅ لیست پیش‌فرض کاراکترهای نامعتبر — immutable و global
DEFAULT_INVALID_CHARS: ClassVar[FrozenSet[str]] = frozenset(
{
"\u001f",
"\u001e",
"\u000b",
"\u0002",
"\u0007",
"„","΄",
"",
"°",
"´",
"Ã",
"É",
"Í",
"Ï",
"×",
"Û",
"à",
"á",
"ã",
"ä",
"ç",
"è",
"é",
"ê",
"í",
"ï",
"ñ",
"ó",
"õ",
"ö",
"ø",
"ú",
"ü",
"þ",
"ÿ",
"ā",
"Ă",
"Ĉ",
"Ĥ",
"Ŋ",
"ˇ",
"ࠤ",
"࠮",
"ࡸ",
"ࢆ",
"Ḩ",
"ḭ",
"Ḿ",
"Ṏ",
"Ἂ",
"Ῥ",
"\u0001",
"\u0000",
"¢",
"£",
"¤",
"μ",
"π",
"Щ",
"؀",
"ऀ",
"ऌ",
"ऎ",
"ऐ",
"द",
"ऴ",
"ू",
"ॄ",
"ॆ",
"ग़",
"ड़",
"চ",
"জ",
"৤",
"০",
"৪",
"৮",
"ਢ",
"ਤ",
"ੋ",
"੒",
"ੜ",
"ઈ",
"଀",
"଎",
"஘",
"௚",
"ా",
"౔",
"ೂ",
"ඊ",
"ฃ",
"ด",
"ฮ",
"โ",
"ไ",
"๒",
"ༀ",
"ᆘ",
"ᆦ",
"ᐨ",
"ᑪ",
"ᒂ",
"ᒶ",
"ᔟ",
"ᔢ",
"ᔧ",
"ᔪ",
"ᘀ",
"ᘂ",
"ᨾ",
"ᰀ",
"᱊",
" ",
"‌",
"‍",
"‘",
"’",
"…",
"‪",
"‬",
"⁋",
"",
"™",
"↓",
"≥",
"⍤",
"␂",
"␃",
"⒢",
"◮",
"⚚",
"⚜",
"⛾",
"⡯",
"⤦",
"⤨",
"ⱆ",
"ⱶ",
"ま",
"㈬",
"㈮",
"㈺",
"㈼",
"㛸",
"㝶",
"㩴",
"㪐",
"㵹",
"㸐",
"㸒",
"䂨",
"䌀",
"䐀",
"䑶",
"䑸",
"䗜",
"䠨",
"䡟",
"䢪",
"䩞",
"䩡",
"䭨",
"䭪",
"䳸",
"䴮",
"䴰",
"伀",
"偦",
"偨",
"儀",
"凄",
"刐",
"刚",
"唃",
"唎",
"唢",
"唤",
"喈",
"喡",
"娀",
"宜",
"屨",
"恨",
"惄",
"愀",
"愔",
"掋",
"摧",
"撆",
"桨",
"汊",
"汌",
"淄",
"皆",
"稀",
"笺",
"筠",
"筨",
"箜",
"篃",
"絘",
"脈",
"茊",
"茌",
"菈",
"蕞",
"蚞",
"譨",
"軺",
"輒",
"輔",
"辜",
"酠",
"鉦",
"鉼",
"鉾",
"銨",
"镖",
"闎",
"餸",
"馼",
"髄",
"魰",
"鶊",
"ꅨ",
"ꉣ",
"ꍀ",
"ꡨ",
"꡻",
"ꢆ",
"ꢘ",
"꣜",
"넣",
"뫜",
"뺨",
"뻪",
"쌀",
"쫮",
"쵕",
"케",
"퓪",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"�",
}
)
# ✅ جدول پیش‌فرض (یکبار محاسبه می‌شود)
_DEFAULT_TRANSLATION_TABLE: ClassVar[dict] = str.maketrans(
"", "", "".join(DEFAULT_INVALID_CHARS)
)
def __init__(
self, options=None, pattern_normalize=None, pattern_hamze_normalize=None
):
"""for Use and Dev
(re.compile(r""), ""),
"""
self.options = (
options
if options
else {
"charArNormal": True,
"errorLine": True,
"alphabetsNormal": False,
"removeInvalidChar": False,
"emptylinesNormal": False,
"hamzehNormal": False,
"spaceCorrection": False,
"trimLine": False,
}
)
self.valid_charset = self.__extract_valid_chars()
if pattern_normalize:
self.pattern_normalize = pattern_normalize
else:
self.pattern_normalize = TextNormalizer.CHAR_PATTERN_MONIR
if pattern_hamze_normalize:
self.pattern_hamze_normalize = pattern_hamze_normalize
else:
self.pattern_hamze_normalize = TextNormalizer.HAMZE_PATTERN
self.pattern_emptylinesnormal = TextNormalizer.EMPTY_LINE_PATTERN
def __extract_valid_chars(self):
valid = set()
for regex, replacement in TextNormalizer.CHAR_PATTERN_MONIR:
# چون replacement ممکن است بیش از یک کاراکتر باشد
for ch in replacement:
valid.add(ch)
return valid
def normalize_text_monir(self, text: str) -> str:
if text == "":
return ""
text = text.strip()
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
if self.options.get("alphabetsNormal", False):
text = self.alphabets_normalize(text)
# حذف کاراکتر های نامعتبر
if self.options.get("removeInvalidChar", False):
text = self.remove_invalid_chars(text)
# نرمال کردن حروف اختلافی عربی و فارسی
# if self.options.get("charArNormal", True):
# text = self.yeke_normal(text)
# پرش از اختلافات همزه‌ا
if self.options.get("hamzehNormal", False):
text = self.hamze_normalize(text)
# حذف خطوط و فاصله‌های خالی
if self.options.get("emptylinesNormal", False):
text = self.emptylines_normalize(text)
# اصلاح فاصله‌ها در ترکیب کلمات
# if self.options.get("spaceCorrection", False):
# text = self.space_correction(text)
# حذف خطوط اضافی اول و انتهای متن
# if self.options.get("trimLine", False):
# text = text.strip()
return text
def html():
pass
@staticmethod
def remove_invalid_chars(
text: str,
extra_invalid_chars: Optional[Set[str]] = None,
exclude_default: bool = False,
) -> str:
"""
حذف کاراکترهای نامعتبر از متن.
Args:
text: متن ورودی.
extra_invalid_chars: مجموعه‌ای از کاراکترهای اضافی برای حذف.
exclude_default: اگر True باشد، فقط کاراکترهای custom حذف می‌شوند (پیش‌فرض نادیده گرفته می‌شود).
Returns:
متن پاک‌سازی‌شده.
"""
if not text:
return text
# ۱. تعیین مجموعه نهایی کاراکترهای نامعتبر
if exclude_default:
invalid_chars = extra_invalid_chars or set()
else:
invalid_chars = set(TextNormalizer.DEFAULT_INVALID_CHARS)
if extra_invalid_chars:
invalid_chars.update(extra_invalid_chars)
# ۲. اگر مجموعه خالی است → هیچ کاری نکن
if not invalid_chars:
return text
# ۳. ساخت جدول ترجمه (بهینه: فقط وقتی لازم است)
# 🔹 برای بهینه‌سازی بیشتر، می‌توانید cache اضافه کنید (در صورت نیاز)
table = str.maketrans("", "", "".join(invalid_chars))
return text.translate(table)
@staticmethod
def alphabets_normalize(
text: str, quote_map: Optional[List[Tuple[re.Pattern[str], str]]] = None
) -> str:
if text == "":
return ""
mapping = quote_map if quote_map else TextNormalizer.CHAR_PATTERN_MONIR
for pattern, repl in mapping:
text = pattern.sub(repl, text)
return text
@staticmethod
def hamze_normalize(
text: str, quote_map: Optional[List[Tuple[re.Pattern[str], str]]] = None
) -> str:
if text == "":
return ""
mapping = quote_map if quote_map else TextNormalizer.HAMZE_PATTERN
for pattern, repl in mapping:
text = pattern.sub(repl, text)
return text
@staticmethod
def emptylines_normalize(
text: str, quote_map: Optional[List[Tuple[re.Pattern[str], str]]] = None
) -> str:
if text == "":
return ""
mapping = quote_map if quote_map else TextNormalizer.EMPTY_LINE_PATTERN
for pattern, repl in mapping:
text = pattern.sub(repl, text)
for pattern, repl in TextNormalizer.FINALL_LINE_PATTERN:
text = pattern.sub(repl, text)
return text
# TEST M
# ـکشیدگی هایی که به جای _ به کار رفته اند
def keshide_corrected(self, text):
(r"(\d)ـ(\d)", r"\1_\2"), # فاصله بین دو عدد
(r"(\d)ـ", r"\1_"), # عدد و خط تیره
(r"ـ(\d)", r"_\1"), # خط تیره و عدد
(r"\sـ\s", r" _ "), # فاصله‌های خالی بین خط تیره
(
r"(?<![ویهبتثجحخدذرزسشصضطظعغفقكلمنپچژکگ])ـ(?![ویهبتثجحخدذرزسشصضطظعغفقكلمنپچژکگ])",
r"_",
),
(r"\sـ\s", r" _ "),
pass
+34 -20
View File
@@ -1,13 +1,15 @@
# --------------------------- modularity # --------------------------- modularity
from idataparser import (
DataHelper, import os
ElasticHelper, import sys
InitTextNormalizer, sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
DataHelper,
save_orjson, from app.common.elastic_helper import ElasticHelper
load_orjson, from app.common.general_functions import getTitleType
) from app.monir.monir_text_normalizer import TextNormalizer
from .base_model import ( from app.common.data_helper import DataHelper
from app.monir.base_model import (
MnTerm, MnTerm,
MnMeetEntity, MnMeetEntity,
MnMeet, MnMeet,
@@ -31,7 +33,7 @@ from dotenv import load_dotenv
input_es_index_name = "" input_es_index_name = ""
new_index_name = "mn_meet" new_index_name = "mn_meet"
old_index_name = "mn_sanad" old_index_name = "mn_sanad"
NORMALIZER = InitTextNormalizer( NORMALIZER = TextNormalizer(
options={ options={
"alphabetsNormal": True, "alphabetsNormal": True,
"emptylinesNormal": True, "emptylinesNormal": True,
@@ -235,24 +237,32 @@ def get_mn_sanad(data: dict) -> MnSanad2Meet:
return MnSanad2Meet.model_validate(data) return MnSanad2Meet.model_validate(data)
def get_term_info(term_data: MnTerm) -> Properties: def get_term_info(term_data) -> dict:
if term_data :
data = Properties( data = Properties(
author=term_data.author, author=term_data.author,
id=term_data.id, id=term_data.id,
sub_type=term_data.sub_type, sub_type=term_data.sub_type,
title=term_data.title, title=term_data.title,
) )
return data # print('-'*10)
# print(type(data))
# print(data)
# print('-'*10)
return data.model_dump()
return None
def get_mn_meet_info(meet_data: MnMeet) -> Properties: def get_mn_meet_info(meet_data: MnMeet) -> dict:
if meet_data :
data = Properties( data = Properties(
author=meet_data.author, author=meet_data.author,
id=meet_data.id, id=meet_data.id,
sub_type=meet_data.sub_type, sub_type=meet_data.sub_type,
title=meet_data.title, title=meet_data.title,
) )
return data return data.model_dump()
return None
def get_report_info(data: MnSanad2Meet) -> ReportInfo: def get_report_info(data: MnSanad2Meet) -> ReportInfo:
@@ -292,8 +302,8 @@ def normalize_field(data: MnSanad2Meet) -> MnSanad2Meet:
def get_mn_meet_entity( def get_mn_meet_entity(
sanad_data: MnSanad2Meet, sanad_data: MnSanad2Meet,
meet_info: Properties, meet_info: dict,
term_info: Properties, term_info,
dict_return=True, dict_return=True,
) -> List[MnMeetEntity]: ) -> List[MnMeetEntity]:
# content # content
@@ -344,7 +354,7 @@ def get_mn_meet_entity(
def get_mn_meet( def get_mn_meet(
sanad_data: MnSanad2Meet, sanad_data: MnSanad2Meet,
term_info: Properties, term_info,
subjects: Subjects, subjects: Subjects,
report_info: ReportInfo, report_info: ReportInfo,
) -> MnMeet: ) -> MnMeet:
@@ -500,6 +510,8 @@ def convert_mn(
# save-term # save-term
# save_orjson(data=term_data.model_dump(), path="./term_1.json") # save_orjson(data=term_data.model_dump(), path="./term_1.json")
if term_data :
term_data = term_data.model_dump() term_data = term_data.model_dump()
es_helper.update_index_doc( es_helper.update_index_doc(
is_update_state=False, is_update_state=False,
@@ -542,7 +554,7 @@ def convert_mn(
traceback.print_exc() traceback.print_exc()
break break
save_orjson(data=phase_1, path="./meet_test_1_data.json") DataHelper.save_orjson(data=phase_1, path="./meet_test_1_data.json")
print( print(
"✅ Data-Created", "✅ Data-Created",
" - saved-> mn_meet", " - saved-> mn_meet",
@@ -571,6 +583,7 @@ def get_old_sanads(hits_list):
# --------------------------- flow # --------------------------- flow
load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_60") host = os.getenv("HOST_60")
password = os.getenv("HOST_60_PASS") password = os.getenv("HOST_60_PASS")
@@ -655,6 +668,7 @@ old_data = list(
index=old_index_name, index=old_index_name,
query={ query={
"_source": fields, "_source": fields,
"size": 10,
"query": "query":
# {"ids": {"values": ["pm146821"]}}, # {"ids": {"values": ["pm146821"]}},
{"match_all": {}}, {"match_all": {}},
@@ -686,8 +700,8 @@ convert_mn(
meet_index_name=meet_index_name, meet_index_name=meet_index_name,
ment_index_name=ment_index_name, ment_index_name=ment_index_name,
) )
save_orjson( DataHelper.save_orjson(
path=r"D:\init_mahdi\project\dataParsers\idataparser\task\monir\informations\finall_result_sanads.json", path=r"./data/monir/finall_result_sanads.json",
data=FINALL_STAT_SANADS, data=FINALL_STAT_SANADS,
) )
# # --------------------------- RUN # # --------------------------- RUN
Binary file not shown.
+449
View File
@@ -0,0 +1,449 @@
import fitz, random, os
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
from typing import Union, List
from PIL import Image, ImageDraw, ImageFont
import math
print(fitz.version) # مثلاً ('1.24.4', '...', ...)
# ---------- تنظیمات شما ----------
INPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\in_test")
# INPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\in_test\4712")
OUTPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\o_test")
WATERMARK_TEXT = [
" معاونت قوانین مجلس شورای اسلامی",
"اداره کل اسناد و اطلاع رسانی قوانین",
]
WATERMARK2_TEXT = "قانون‌یار"
DPI = 150
MAX_SIZE = 300
# ----------------------------------
FONT_PATH = r"Iranian Sans.ttf"
SUPPORTED_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".tif"}
SUPPORTED_PDF_EXTS = {".pdf"}
import random
from pathlib import Path
from typing import Union, List, Tuple
from PIL import Image, ImageDraw, ImageFont
def add_watermark(
img: Image.Image,
primary_text: Union[str, List[str]],
sec_text: str,
font_path: str = FONT_PATH,
primary_opacity: int = 50,
secondary_opacity: int = 15,
grid_rows: int = 10, # ✅ تعداد سطرهای شبکه
grid_cols: int = 1, # ✅ تعداد ستون‌های شبکه
rotation_range: Tuple[int, int] = (-15, 13),
font_size_primary: int = 16,
font_size_secondary: int = 10,
) -> Image.Image:
"""
اعمال واترمارک:
- primary: شبکه‌ای (grid_rows × grid_cols)، هر سلول یک متن تصادفی، موقعیت و زاویه رندوم درون سلول
- secondary: فقط 4 گوشه
"""
img = img.convert("RGBA")
width, height = img.size
# ===== بارگذاری فونت =====
def get_font(size):
if font_path and Path(font_path).exists():
return ImageFont.truetype(font_path, size)
for fallback in ["Arial.ttf", "DejaVuSans.ttf", "NotoSans-Regular.ttf"]:
try:
return ImageFont.truetype(fallback, size)
except OSError:
continue
return ImageFont.load_default()
font_p = get_font(font_size_primary)
font_s = get_font(font_size_secondary)
draw = ImageDraw.Draw(img)
# ===== کمک‌تابع: رسم متن با حاشیه و opacity =====
def draw_text_with_stroke(
draw_obj, xy, text, font, fill_color, stroke_color, opacity, stroke_width=1
):
x, y = xy
fill = (
(*fill_color[:3], int(fill_color[3] * opacity / 255))
if len(fill_color) == 4
else (*fill_color, opacity)
)
stroke = (
(*stroke_color[:3], int(stroke_color[3] * opacity / 255))
if len(stroke_color) == 4
else (*stroke_color, opacity)
)
for dx in range(-stroke_width, stroke_width + 1):
for dy in range(-stroke_width, stroke_width + 1):
if dx == 0 and dy == 0:
continue
draw_obj.text((x + dx, y + dy), text, font=font, fill=stroke)
draw_obj.text((x, y), text, font=font, fill=fill)
# ===== 1. واترمارک ثانویه: فقط 4 گوشه =====
if sec_text.strip():
bbox = draw.textbbox((0, 0), sec_text, font=font_s)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
padding = 10
corners = [
(padding, padding),
(width - tw - padding, padding),
(padding, height - th - padding),
(width - tw - padding, height - th - padding),
]
for x, y in corners:
draw_text_with_stroke(
draw,
(x, y),
sec_text,
font_s,
fill_color=(255, 255, 255),
stroke_color=(0, 0, 0),
opacity=secondary_opacity,
stroke_width=1,
)
# ===== 2. واترمارک اصلی: شبکه‌بندی + رندوم درون هر سلول =====
primary_texts = (
[primary_text]
if isinstance(primary_text, str)
else [t for t in primary_text if t.strip()]
)
if not primary_texts:
return img.convert("RGB")
# اندازه هر سلول
cell_width = width / grid_cols
cell_height = height / grid_rows
# حداکثر ابعاد متن برای جلوگیری از خروج از سلول (اجباری نیست، اما برای بهینه‌سازی موقعیت تصادفی مفید است)
max_tw, max_th = 0, 0
for txt in primary_texts:
bbox = draw.textbbox((0, 0), txt, font=font_p)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
max_tw = max(max_tw, tw)
max_th = max(max_th, th)
# ✅ اصلاح: حاشیه ایمنی کوچک‌تر و منطقی‌تر برای حالت ستونی
# اجازه دهید متن تا ~30% پهنای سلول جابجا شود (نه محدود به safe_w که وقتی grid_cols=1 خیلی بزرگ است!)
offset_limit_x = min(cell_width * 0.3, max_tw * 1.5) # max انحراف افقی
offset_limit_y = min(cell_height * 0.4, max_th * 2.0) # max انحراف عمودی
for row in range(grid_rows):
for col in range(grid_cols):
# محدوده سلول
x0 = col * cell_width
y0 = row * cell_height
x1 = x0 + cell_width
y1 = y0 + cell_height
text = random.choice(primary_texts).strip()
if not text:
continue
# ابعاد دقیق متن
bbox = draw.textbbox((0, 0), text, font=font_p)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
# ✅ موقعیت پایه: یک نقطه داخل سلول، نه الزاماً مرکز
# مثلاً 20%~80% عرض سلول و 30%~70% ارتفاع سلول
base_x = x0 + random.uniform(0.2, 0.8) * cell_width
base_y = y0 + random.uniform(0.3, 0.7) * cell_height
# ✅ انحراف تصادفی در محدوده منطقی (نه بسته به safe_w که گاهی صفر می‌شد)
dx = random.uniform(-offset_limit_x, offset_limit_x)
dy = random.uniform(-offset_limit_y, offset_limit_y)
final_x = max(0, min(width - 1, base_x + dx))
final_y = max(0, min(height - 1, base_y + dy))
# ✅ زاویه تصادفی
angle = random.randint(*rotation_range)
# ساخت لایه متن
pad = 20 # padding around text for rotation
layer_w, layer_h = int(tw + 2 * pad), int(th + 2 * pad)
txt_layer = Image.new("RGBA", (layer_w, layer_h), (0, 0, 0, 0))
d = ImageDraw.Draw(txt_layer)
draw_text_with_stroke(
d,
(pad, pad), # متن از گوشه شروع می‌شود — ساده‌تر و دقیق‌تر
text,
font_p,
fill_color=(255, 255, 255),
stroke_color=(0, 0, 0),
opacity=primary_opacity,
stroke_width=1,
)
rotated = txt_layer.rotate(angle, expand=True, resample=Image.BICUBIC)
rw, rh = rotated.size
# موقعیت نهایی: مرکز لایه چرخیده روی (final_x, final_y)
pos_x = int(final_x - rw / 2)
pos_y = int(final_y - rh / 2)
pos_x = max(0, min(pos_x, width - rw))
pos_y = max(0, min(pos_y, height - rh))
img.alpha_composite(rotated, (pos_x, pos_y))
return img.convert("RGB")
def create_thumbnail(
img: Image.Image,
max_width: int = 300, # ✅ فقط عرض هدف — ارتفاع پویا
method: str = "width", # "width", "height", "contain", "cover"
bg_color: tuple = (255, 255, 255),
antialias: bool = True,
) -> Image.Image:
"""
تولید تامنیل با کنترل دقیق ابعاد.
method:
- "width": عرض = max_width، ارتفاع متناسب (نسبت حفظ می‌شود)
- "height": ارتفاع = max_width (نام پارامتر حفظ شد)، عرض متناسب
- "contain": مربع با حاشیه
- "cover": مربع با برش
"""
img = img.copy()
# تبدیل حالت برای پردازش
if img.mode in ("RGBA", "LA", "P"):
img = img.convert("RGBA")
else:
img = img.convert("RGB")
orig_w, orig_h = img.size
# انتخاب resampling
resample = (
Image.Resampling.LANCZOS
if (antialias and hasattr(Image, "Resampling"))
else Image.LANCZOS
)
# ✅ روش جدید: فقط عرض تنظیم شود — ارتفاع نسبتی
if method == "width":
if orig_w == 0:
raise ValueError("عرض تصویر نمی‌تواند صفر باشد")
ratio = max_width / orig_w
new_w = max_width
new_h = int(orig_h * ratio)
return img.resize((new_w, new_h), resample=resample).convert("RGB")
elif method == "height":
if orig_h == 0:
raise ValueError("ارتفاع تصویر نمی‌تواند صفر باشد")
ratio = max_width / orig_h # max_width اینجا به معنای max_height است!
new_h = max_width
new_w = int(orig_w * ratio)
return img.resize((new_w, new_h), resample=resample).convert("RGB")
# --- بقیه روش‌های قبلی ---
elif method == "contain":
ratio = min(max_width / orig_w, max_width / orig_h)
new_w = int(orig_w * ratio)
new_h = int(orig_h * ratio)
img = img.resize((new_w, new_h), resample=resample)
thumb = Image.new("RGB", (max_width, max_width), bg_color)
x = (max_width - new_w) // 2
y = (max_width - new_h) // 2
if img.mode == "RGBA":
thumb.paste(img, (x, y), img)
else:
thumb.paste(img, (x, y))
return thumb
elif method == "cover":
ratio = max(max_width / orig_w, max_width / orig_h)
new_w = int(orig_w * ratio)
new_h = int(orig_h * ratio)
img = img.resize((new_w, new_h), resample=resample)
left = (new_w - max_width) // 2
top = (new_h - max_width) // 2
return img.crop((left, top, left + max_width, top + max_width)).convert("RGB")
else:
raise ValueError("method must be 'width', 'height', 'contain', or 'cover'")
def process_image(input_path: Path, output_path: Path):
try:
with Image.open(input_path) as img:
# تبدیل حالت
if img.mode in ("RGBA", "LA", "P"):
img = img.convert("RGBA")
elif img.mode in ("I", "I;16", "F"):
img = img.convert("RGB")
elif img.mode == "CMYK":
img = img.convert("RGB")
else:
img = img.convert("RGB")
# ✅ ایجاد تامنیل (مثلاً 300px)
img = create_thumbnail(
img,
max_width=MAX_SIZE,
method="width",
bg_color=(255, 255, 255),
)
# اعمال واترمارک
img = add_watermark(
img=img,
primary_text=WATERMARK_TEXT,
sec_text=WATERMARK2_TEXT,
)
# ذخیره — DPI دیگر مهم نیست، ولی برای ثبت متادیتا می‌گذاریم
img.save(
output_path,
format="JPEG",
dpi=(72, 72), # یا هر چیزی — تأثیری ندارد
quality=85, # کیفیت فشرده‌سازی (80-90 برای تامنیل مناسب است)
optimize=True,
)
print(f"✅ Thumbnail saved: {output_path} | Size: {img.size}")
except Exception as e:
print(f"❌ Image Error {input_path}: {e}")
def is_image_mostly_white(
img: Image.Image, white_threshold: int = 240, white_ratio: float = 0.95
) -> bool:
"""
بررسی می‌کند که آیا تصویر عمدتاً سفید است.
:param img: تصویر PIL (ترجیحاً RGB)
:param white_threshold: مقدار آستانه برای سفید بودن یک پیکسل (0–255). مثلاً 240 یعنی R,G,B ≥ 240
:param white_ratio: نسبت پیکسل‌های سفید لازم برای در نظر گرفتن تصویر به عنوان "خالی" (مثلاً 0.95 = 95%)
:return: True اگر تصویر عمدتاً سفید باشد
"""
img = img.convert("RGB")
arr = np.array(img)
# تعداد پیکسل‌هایی که R,G,B همگی ≥ white_threshold
# شکل arr: (height, width, 3)
white_pixels = np.sum(
(arr[:, :, 0] >= white_threshold)
& (arr[:, :, 1] >= white_threshold)
& (arr[:, :, 2] >= white_threshold)
)
total_pixels = arr.shape[0] * arr.shape[1]
ratio = white_pixels / total_pixels
return ratio >= white_ratio
def process_pdf(input_path: Path, output_path: Path):
"""صفحه اول غیرخالی PDF را با 24 DPI رندر می‌کند، اما تصویر نهایی را به MAX_SIZE تغییر اندازه می‌دهد."""
try:
doc = fitz.open(input_path)
if doc.page_count == 0:
print(f"⚠️ PDF is Empty: {input_path}")
doc.close()
return
zoom = DPI / 72.0
mat = fitz.Matrix(zoom, zoom)
target_page = None
target_pix = None
for page_num in range(doc.page_count):
page = doc.load_page(page_num)
pix = page.get_pixmap(matrix=mat)
# فقط برای تست خالی بودن — نه نهایی!
img_check = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
img_thumb = create_thumbnail(
img_check, max_width=MAX_SIZE, method="width", bg_color=(255, 255, 255)
)
if not is_image_mostly_white(img_thumb, white_threshold=240, white_ratio=0.95):
target_page = page_num
target_pix = pix
print(f"📄 Page {page_num + 1} selected (non-empty) in {input_path.name}")
break
if target_pix is None:
print(f"❗ All pages empty; using page 1: {input_path}")
page = doc.load_page(0)
target_pix = page.get_pixmap(matrix=mat)
# ✅ تبدیل واقعی به تصویر + تامنیل‌سازی
img = Image.frombytes("RGB", [target_pix.width, target_pix.height], target_pix.samples)
img = create_thumbnail( # ← این خط جدید کل مشکل را حل می‌کند
img,
max_width=MAX_SIZE,
method="width",
bg_color=(255, 255, 255),
antialias=True,
)
# اعمال واترمارک
img = add_watermark(
img=img,
primary_text=WATERMARK_TEXT,
sec_text=WATERMARK2_TEXT,
font_size_primary=12, # کمی کاهش برای تامنیل
primary_opacity=60,
)
# ذخیره
out_img_path = output_path.with_suffix(".jpg") # یا .png
img.save(
out_img_path,
format="JPEG",
dpi=(DPI, DPI), # فقط برای متادیتا — اندازه پیکسلی از img.size می‌آید
quality=85,
optimize=True,
)
doc.close()
print(f"✅ PDF Thumbnail Saved: {out_img_path} | Size: {img.size}")
except Exception as e:
print(f"❌ PDF Error {input_path}: {e}")
import traceback
traceback.print_exc()
def copy_and_process_structure(input_dir: Path, output_dir: Path):
for root, dirs, files in os.walk(input_dir):
rel_path = Path(root).relative_to(input_dir)
target_dir = output_dir / rel_path
target_dir.mkdir(parents=True, exist_ok=True)
for file in files:
src_file = Path(root) / file
ext = src_file.suffix.lower()
if ext in SUPPORTED_IMAGE_EXTS:
dst_file = (target_dir / src_file.stem).with_suffix(".jpg")
process_image(src_file, dst_file)
elif ext in SUPPORTED_PDF_EXTS:
# حفظ نام فایل اما تبدیل به تصویر (پسوند عوض می‌شود به .png)
dst_file = target_dir / src_file.stem # بدون پسوند
process_pdf(src_file, dst_file)
else:
print(f"⏭️ This File {src_file} Not Supported Ext")
# ========== اجرای اصلی ==========
if __name__ == "__main__":
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"Start from {INPUT_DIR} to {OUTPUT_DIR}")
copy_and_process_structure(INPUT_DIR, OUTPUT_DIR)
print("End")
print(":D")
@@ -53,6 +53,11 @@ def correct_qanon_date_json(data, error_list):
item["_source"], "expire_date", error_list, id, "" item["_source"], "expire_date", error_list, id, ""
) )
if "date_edit" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "date_edit", error_list, id, ""
)
if "fixed_date" in item["_source"]: if "fixed_date" in item["_source"]:
item["_source"] = repair_object_persian_date( item["_source"] = repair_object_persian_date(
item["_source"], "fixed_date", error_list, id, "" item["_source"], "fixed_date", error_list, id, ""
@@ -265,9 +270,9 @@ def import_content_opinion_to_qaqanon(elastic, path_file, index_name_o):
if ts_date: if ts_date:
data["ts_date"] = ts_date data["ts_date"] = ts_date
if expire_date: if expire_date:
data["ts_date"] = expire_date data["expire_date"] = expire_date
if aproveDate: if aproveDate:
data["ts_date"] = aproveDate data["exec_date"] = aproveDate
if html: # ساختن دوباره و بهتر if html: # ساختن دوباره و بهتر
content = html_to_text_preserve_lines(html) content = html_to_text_preserve_lines(html)
+1
View File
@@ -0,0 +1 @@
[]
+7
View File
@@ -7,3 +7,10 @@ pandas
openpyxl openpyxl
mistralai mistralai
orjson orjson
pydantic
jdatetime
pillow
fitz