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
+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 از فایل اکسل و تبدیل به لیست دیکشنری.