run_codes_extract_directory

This commit is contained in:
hsafaei
2025-12-04 13:47:58 +03:30
parent e616d748c5
commit 1c6d446110
8 changed files with 960 additions and 382 deletions
+40 -13
View File
@@ -580,7 +580,7 @@ class ElasticHelper:
# - داده‌ها را به صورت bulk آپدیت می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def updateBulkList(self, listData, index_name):
def updateBulkList(self, listData, index_name, streem_state=False):
chunk_size = 100000
raise_on_error = False
raise_on_exception = False
@@ -597,15 +597,28 @@ class ElasticHelper:
"doc": item["_source"],
}
)
helpers.bulk(
self.es,
actions,
chunk_size,
raise_on_error,
raise_on_exception,
stats_only,
yield_ok,
)
if streem_state :
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
actions,
raise_on_error=False,
raise_on_exception=False,
):
if not ok:
print("Error:", result)
else :
helpers.bulk(
self.es,
actions,
chunk_size,
raise_on_error,
raise_on_exception,
stats_only,
yield_ok,
)
# ----------------------------start---------------------------
# متد importBulkList:
@@ -617,22 +630,36 @@ class ElasticHelper:
# - داده‌ها را به صورت bulk وارد می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def importBulkList(self, listData, index_name):
def importBulkList(self, listData, index_name, streem_state=False):
chunk_size = 100000
raise_on_error = False
raise_on_exception = False
stats_only = True
yield_ok = False
actions=[]
for item in listData:
actions = [
actions.append(
{
"_op_type": "index",
"_index": index_name,
"_id": item["_id"],
"_source": item["_source"],
}
]
)
if streem_state :
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
actions,
raise_on_error=False,
raise_on_exception=False,
):
if not ok:
print("Error:", result)
else :
helpers.bulk(
self.es,
actions,
+109 -1
View File
@@ -5,7 +5,7 @@ import re
import sys
from re import sub
import textwrap
from html import escape
from html import escape, unescape
from bs4 import BeautifulSoup
import json
from decimal import Decimal
@@ -13,6 +13,8 @@ import traceback
# from lxml import etree
import datetime
from datetime import timedelta
import pandas as pd
#enumerate(token_list):
_normalizer = Normalizer(date_normalizing_needed=True)
@@ -62,6 +64,52 @@ def isNeedHtml(html):
else:
return False
def html_to_text_preserve_lines(html_str: str) -> str:
"""
Convert HTML -> plain text while preserving line breaks for tags like
<p>, <br>, <li>, <tr>/<td> (tables) etc.
"""
soup = BeautifulSoup(html_str, "html.parser")
# <br> -> newline
for br in soup.find_all("br"):
br.replace_with("\n")
# <p> -> ensure separated paragraphs (one blank line between paragraphs)
for p in soup.find_all("p"):
# put newline before and after paragraph content (avoid duplicate)
p.insert_before("\n")
p.append("\n")
# <li> -> prefix with "- " and newline before each item
for li in soup.find_all("li"):
li.insert_before("\n- ")
# keep li content as-is; ensure newline after
li.append("\n")
# table: make cells separated by tabs and rows end with newline
for td in soup.find_all(["td", "th"]):
# append a tab after each cell (so cells become column-separated)
td.append("\t")
for tr in soup.find_all("tr"):
tr.append("\n")
# Optional: collapse multiple consecutive whitespace-only newlines later
text = soup.get_text()
# convert HTML entities (&amp; &nbsp; etc.)
text = unescape(text)
# Normalize: convert runs of >2 newlines to max 2, strip trailing spaces on lines
text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text) # 3+ newlines -> 2
text = '\n'.join(line.rstrip() for line in text.splitlines()) # rstrip each line
text = text.strip("\n ") # remove leading/trailing blanks/newlines
# convert tabs used for table cells to single spaces if you prefer:
text = text.replace("\t", " ") # or keep \t for programmatic use
return text
# erab
def remove_arabic_diacritics(text):
# Regular expression to match all Arabic diacritics
@@ -423,6 +471,20 @@ def jdate2Gregorian(text):
def dateTimestamp(gdate):
empty_date = -15000000000
ts_ts = empty_date
try:
base = datetime.datetime(1970, 1, 1)
gd = datetime.datetime.strptime(gdate, "%Y-%m-%d")
rr = (gd-base).total_seconds()
ts_ts = int( round(rr) * 1000)
except Exception as e:
ts_ts = empty_date
return ts_ts
def getSortTimestamp(ts_date):
empty_date = -15000000000
ts_ts = empty_date
@@ -1134,12 +1196,20 @@ def myTimestamp(days=0):
#////////////////////////////////////////////////////////////
#////////////////////////////////////////////////////////////
def is_match_persian_date_format(text):
#چون NaN تنها مقداری است که خودش با خودش برابر نیست
if not text or text != text : # True اگر NaN باشد:
return False
text = str(text)
if text == '0000/00/00' :
return False
if text == '00/00/00' :
return False
# items = text.split('/')
pattern = r'\d{4}/\d{1,2}/\d{1,2}'
@@ -1148,6 +1218,44 @@ def is_match_persian_date_format(text):
return False
def convert_persian_date(value):
res = ''
_date = value
if not _date or _date == '' :
return res, ''
#چون NaN تنها مقداری است که خودش با خودش برابر نیست
if _date != _date : # True اگر NaN باشد:
return res, ''
if _date and not is_match_persian_date_format(_date):
return res, "error match_persian_date_format"
if _date :
try :
res = jdate2Gregorian(_date)
except Exception as e:
return res, "error convert persian_date"
return res, ''
def repair_object_persian_date(item, key, error_list=None, id='', key2=''):
res = ''
path_key = key2+'.'+key if key2 else key
if key in item :
_date = item[key]
res, error = convert_persian_date(_date)
if not res :
if not error_list is None :
error_list.append({'id':id, 'key': path_key, "value":_date, "message": error })
del item[key]
return item
if res :
item[key] = res
return item
def excel_to_json(excel_file, required_columns=None, sheet_name=0):
"""
خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری.
+9 -6
View File
@@ -202,7 +202,7 @@ def get_dict_qanon_title(file_path):
return dict
def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_qa_section"):
def searchQanonTitleOfContent(elastic, qanon_title, ts_date="", index_name="mj_qa_section"):
score = 100
@@ -254,12 +254,12 @@ def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_q
if len(list_equal) == 1 :
item = list_equal[0]
score = 90
if ts_data == item['_source']['ts_date'] :
if ts_date == ts_date_ref :
score = 100
return item['_source']["qanon_id"], score, item
for item in list_equal :
if ts_data == item['_source']['ts_date'] :
if ts_date == ts_date_ref :
score = 100
return item['_source']["qanon_id"], score, item
@@ -271,7 +271,7 @@ def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_q
return 0, 0, {}
def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon", ts_ref=""):
def searchQanonId(elastic, qanon_title, ts_date="", index_name="mj_qa_qanon", ts_ref=""):
score = 100
body = {
"query": {
@@ -332,15 +332,18 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon", ts
if title_sample == qanon_title_sample or title_sample == qanon_title_sample2:
list_equal.append(item)
ts_date_ref = ''
if 'ts_date' in item['_source'] :
ts_date_ref = item['_source']['ts_date']
if len(list_equal) == 1 :
item = list_equal[0]
score = 90
if ts_data == item['_source']['ts_date'] :
if ts_date == ts_date_ref :
score = 100
return item["_id"], score, item
for item in list_equal :
if ts_data and ts_data == item['_source']['ts_date'] :
if ts_date and ts_date == ts_date_ref :
score = 100
return item["_id"], score, item
+20 -6
View File
@@ -57,6 +57,10 @@ class TextNormalizer:
def normalize_qanon(self, text, error_state=False):
if not text:
return ""
#چون NaN تنها مقداری است که خودش با خودش برابر نیست
if text != text : # True اگر NaN باشد:
return ""
text = text.strip()
# اصلاح خطاهای متن در کد خط
@@ -315,7 +319,7 @@ class TextNormalizer:
return text
def date_correction(self, text):
def date_correction(self, text, day_to_year=True):
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text)
text = re.sub(r"(\d+?)ر(\d+?)", r"\1/\2", text)
@@ -326,11 +330,21 @@ class TextNormalizer:
# # فرمت YYYY/MM/DD یا YYYY-MM-DD --> YYYY/MM/DD
# text = re.sub(r'(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})', r'\1/\2/\3', text)
# فرمت DD/MM/YYYY یا DD-MM-YYYY ---> YYYY/MM/DD
text = re.sub(r"(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\3/\2/\1", text)
text = re.sub(r" (\d{1})[\/\-](\d{1})[\/\-](\d{4})", r" 0\1/0\2/\3", text)
text = re.sub(r" (\d{1})[\/\-](\d{2})[\/\-](\d{4})", r" 0\1/\2/\3", text)
text = re.sub(r" (\d{2})[\/\-](\d{1})[\/\-](\d{4})", r" \1/0\2/\3", text)
if not day_to_year :
# فرمت DD/MM/YYYY یا DD-MM-YYYY ---> YYYY/MM/DD
text = re.sub(r"^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\1/\2/\3", text)
text = re.sub(r"^(\d{2})[\/\-](\d{2})[\/\-](\d{4})", r"\3/\2/\1", text)
text = re.sub(r"^(\d{1})[\/\-](\d{1})[\/\-](\d{4})", r"\3/0\2/0\1", text)
text = re.sub(r"^(\d{1})[\/\-](\d{2})[\/\-](\d{4})", r"\3/\2/0\1", text)
text = re.sub(r"^(\d{2})[\/\-](\d{1})[\/\-](\d{4})", r"\3/0\2/\1", text)
else :
# فرمت DD/MM/YYYY یا DD-MM-YYYY ---> YYYY/MM/DD
text = re.sub(r"^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\3/\2/\1", text)
text = re.sub(r"^(\d{2})[\/\-](\d{2})[\/\-](\d{4})", r"\1/\2/\3", text)
text = re.sub(r"^(\d{1})[\/\-](\d{1})[\/\-](\d{4})", r"0\1/0\2/\3", text)
text = re.sub(r"^(\d{1})[\/\-](\d{2})[\/\-](\d{4})", r"0\1/\2/\3", text)
text = re.sub(r"^(\d{2})[\/\-](\d{1})[\/\-](\d{4})", r"\1/0\2/\3", text)
return text
def space_correction(self, text):