This commit is contained in:
hsafaei
2025-09-30 09:55:36 +03:30
6 changed files with 718 additions and 96 deletions
+1
View File
@@ -31,3 +31,4 @@ yarn-error.log*
*.sw? *.sw?
*.rar *.rar
*.zip *.zip
analyzed_domains.json
+1 -1
View File
@@ -303,7 +303,7 @@ class Normalizer():
return word in self.date_normalizer.num_dict return word in self.date_normalizer.num_dict
def normalize(self, doc_string, new_line_elimination=False, return_dates = False): def normalize(self, doc_string, new_line_elimination=False, return_dates = False):
normalized_string = normalYehKe(doc_string) normalized_string = self.normalYehKe(doc_string)
normalized_string = self.sub_alphabets(doc_string) normalized_string = self.sub_alphabets(doc_string)
#normalized_string = self.data_helper.clean_text(normalized_string, new_line_elimination).strip() #normalized_string = self.data_helper.clean_text(normalized_string, new_line_elimination).strip()
+137 -34
View File
@@ -1,24 +1,30 @@
import re import re
class TextNormalizer: class TextNormalizer:
def __init__(self, options=None): def __init__(self, options=None):
self.options = options if options else { self.options = (
options
if options
else {
"charArNormal": True, "charArNormal": True,
"errorLine": True, "errorLine": True,
"alphabetsNormal": False, "alphabetsNormal": False,
"emptylinesNormal": False, "emptylinesNormal": False,
"hamzehNormal": False, "hamzehNormal": False,
"spaceCorrection": False, "spaceCorrection": False,
"trimLine": False "trimLine": False,
} }
)
def split_words(self, text): def split_words(self, text):
if not text: if not text:
return [] return []
### “” ### “”
words = re.split(r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛ \-!?:٭؟]+", text) words = re.split(
r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛ \-!?:٭؟]+", text
)
return words return words
def normalize_search_qanon(self, text, error_state=False): def normalize_search_qanon(self, text, error_state=False):
@@ -43,7 +49,6 @@ class TextNormalizer:
# نرمال کردن حروف اختلافی عربی و فارسی # نرمال کردن حروف اختلافی عربی و فارسی
text = self.yeke_normal(text) text = self.yeke_normal(text)
# text = self.hamzah_normal(text) # text = self.hamzah_normal(text)
# text = self.alaem_normal(text) # text = self.alaem_normal(text)
@@ -94,7 +99,6 @@ class TextNormalizer:
return text return text
def normalize_text(self, text): def normalize_text(self, text):
if not text: if not text:
return "" return ""
@@ -130,7 +134,9 @@ class TextNormalizer:
return text return text
def alaem_normal(self, text): def alaem_normal(self, text):
text = re.sub(r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛\-!?:٭؟]+", "", text) text = re.sub(
r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛\-!?:٭؟]+", "", text
)
return text return text
def yeke_normal(self, text): def yeke_normal(self, text):
@@ -145,15 +151,14 @@ class TextNormalizer:
text = re.sub(r"إ|أ", "ا", text) text = re.sub(r"إ|أ", "ا", text)
return text return text
def replace_alphabets_error(self, text): def replace_alphabets_error(self, text):
if not text: if not text:
return "" return ""
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص text = re.sub(r"\u00AD|\u00AC", "\u200c", text) # نیم اسپیس خاص
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری text = re.sub(r"(\u002C)+", "\u200c", text) # نیم اسپیس تکراری
text = re.sub(r"ﺁ|آ", "آ", text) text = re.sub(r"ﺁ|آ", "آ", text)
text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text) text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text)
text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text) text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text)
@@ -194,7 +199,7 @@ class TextNormalizer:
text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text) text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text)
text = re.sub(r",|٬|٫|‚|،", "،", text) text = re.sub(r",|٬|٫|‚|،", "،", text)
text = re.sub(r"ʕ", "؟", text) text = re.sub(r"ʕ", "؟", text)
text = re.sub(r"”|“", "\"", text) text = re.sub(r"”|“", '"', text)
text = re.sub(r"۰|٠", "0", text) text = re.sub(r"۰|٠", "0", text)
text = re.sub(r"۱|١", "1", text) text = re.sub(r"۱|١", "1", text)
text = re.sub(r"۲|٢", "2", text) text = re.sub(r"۲|٢", "2", text)
@@ -208,7 +213,9 @@ class TextNormalizer:
text = re.sub(r"²", "2", text) text = re.sub(r"²", "2", text)
text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text) text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text)
text = re.sub(r"ـ", "", text) # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد text = re.sub(
r"ـ", "", text
) # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
return text return text
def replace_alphabets(self, text): def replace_alphabets(self, text):
@@ -217,9 +224,8 @@ class TextNormalizer:
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
text = re.sub(r"\u00AD|\u00AC", "\u200c", text) # نیم اسپیس خاص
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص text = re.sub(r"(\u002C)+", "\u200c", text) # نیم اسپیس تکراری
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری
text = re.sub(r"ﺁ|آ", "آ", text) text = re.sub(r"ﺁ|آ", "آ", text)
text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text) text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text)
text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text) text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text)
@@ -260,7 +266,7 @@ class TextNormalizer:
text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text) text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text)
text = re.sub(r",|٬|٫|‚|،", "،", text) text = re.sub(r",|٬|٫|‚|،", "،", text)
text = re.sub(r"ʕ", "؟", text) text = re.sub(r"ʕ", "؟", text)
text = re.sub(r"”|“", "\"", text) text = re.sub(r"”|“", '"', text)
text = re.sub(r"۰|٠", "0", text) text = re.sub(r"۰|٠", "0", text)
text = re.sub(r"۱|١", "1", text) text = re.sub(r"۱|١", "1", text)
text = re.sub(r"۲|٢", "2", text) text = re.sub(r"۲|٢", "2", text)
@@ -275,13 +281,14 @@ class TextNormalizer:
text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text) text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text)
# text = re.sub(r"ـ", "", text) # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد # text = re.sub(r"ـ", "", text) # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
text = re.sub(r'([\u0600-\u06FF])ـ([\u0600-\u06FF])', r'\1\2', text) # حذف حروف کشیده text = re.sub(
text = re.sub(r'([\u0600-\u06FF])ـ', r'\1', text) # حذف حروف کشیده r"([\u0600-\u06FF])ـ([\u0600-\u06FF])", r"\1\2", text
) # حذف حروف کشیده
text = re.sub(r"([\u0600-\u06FF])ـ", r"\1", text) # حذف حروف کشیده
text = text.strip("\u200C").strip() text = text.strip("\u200c").strip()
return text return text
def date_correction(self, text): def date_correction(self, text):
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text) text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text)
@@ -290,18 +297,16 @@ class TextNormalizer:
text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text) text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text)
# text = re.sub(r"(\d+?) \\(\d+?) \\(\d+?)", r"\1/\2/\3", text) # text = re.sub(r"(\d+?) \\(\d+?) \\(\d+?)", r"\1/\2/\3", text)
# # فرمت YYYY/MM/DD یا YYYY-MM-DD --> YYYY/MM/DD # # فرمت 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) # 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 # فرمت 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{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{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{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) text = re.sub(r" (\d{2})[\/\-](\d{1})[\/\-](\d{4})", r" \1/0\2/\3", text)
return text return text
def space_correction(self, text): def space_correction(self, text):
text = re.sub(r"^(بی|می|نمی)( )", r"\1‌", text) text = re.sub(r"^(بی|می|نمی)( )", r"\1‌", text)
@@ -319,15 +324,22 @@ class TextNormalizer:
) )
return text return text
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند # اعداد چسبیده به کلمات را با یک فاصله جدا می کند
def word_digit_correction(self, text): def word_digit_correction(self, text):
text = re.sub(r"(\200C)(\d+)", r" \2", text) text = re.sub(r"(\200C)(\d+)", r" \2", text)
text = re.sub(r"(\d+)(\200C)", r"\1 ", text) text = re.sub(r"(\d+)(\200C)", r"\1 ", text)
text = re.sub(r"(\200C)([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])", r" \2", text) text = re.sub(
text = re.sub(r"([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])(\200C)", r"\1 ", text) r"(\200C)([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])",
r" \2",
text,
)
text = re.sub(
r"([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])(\200C)",
r"\1 ",
text,
)
# ## شماره22 -> شماره 22 22/ش2 # ## شماره22 -> شماره 22 22/ش2
# ### no ش/22 شد\22 # ### no ش/22 شد\22
@@ -336,7 +348,6 @@ class TextNormalizer:
text = re.sub(r"[^\/](\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1 \2", text) text = re.sub(r"[^\/](\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1 \2", text)
text = re.sub(r"([\u0600-\u06FF\u0750-\u077F]+?)(\d+)", r"\1 \2", text) text = re.sub(r"([\u0600-\u06FF\u0750-\u077F]+?)(\d+)", r"\1 \2", text)
# ر54ر44ر135 # ر54ر44ر135
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1\/\2\/\3", text) text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1\/\2\/\3", text)
text = re.sub(r"(\d+?)ر(\d+?)", r"\1\/\2", text) text = re.sub(r"(\d+?)ر(\d+?)", r"\1\/\2", text)
@@ -355,19 +366,111 @@ class TextNormalizer:
text = re.sub(r"(ی)(های )", r"\1‌\2", text) text = re.sub(r"(ی)(های )", r"\1‌\2", text)
return text return text
def pad_left(self, s, length, char=" "):
def pad_left(self, s, length, char=' '):
if len(s) >= length: if len(s) >= length:
return s return s
else: else:
return char * (length - len(s)) + s return char * (length - len(s)) + s
# erab # erab
def remove_arabic_diacritics(self, text): def remove_arabic_diacritics(self, text):
# Regular expression to match all Arabic diacritics # Regular expression to match all Arabic diacritics
diacritics_pattern = r'[\u064B-\u0652\u0670]' diacritics_pattern = r"[\u064B-\u0652\u0670]"
return re.sub(diacritics_pattern, '', text) return re.sub(diacritics_pattern, "", text)
# TEST M
def replace_full_alphabets_error(self, text):
if not text:
return ""
self.pattern = [
(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"ـ"),
"",
), # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
]
if not text:
return ""
for pattern, repl in self.pattern:
text = pattern.sub(repl, text)
return text
def full_hamzah_normal(self, text):
text = re.sub(r"ئ|ﺌ|ﺋ", "ی", text)
text = re.sub(r"ؤ|ﺅ", "و", text)
text = re.sub(r"ﺔ|ۀ|ﺓ|ة", "ه", text)
text = re.sub(r"إ|أ", "ا", 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
# # تست برنامه # # تست برنامه
+523 -15
View File
@@ -1,11 +1,15 @@
import io import io
import os import os
import json import json
import orjson
from collections import defaultdict from collections import defaultdict
from dotenv import load_dotenv from dotenv import load_dotenv
from app.common.text_normalizer import TextNormalizer from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper from app.common.elastic_helper import ElasticHelper
import pandas as pd
import json
from pathlib import Path
from openpyxl import Workbook
stopwords_fr_sr = "و،شده،از,در,به,را,که,چه,با,تا,بر,ما,شما,ایشان,من,تو,او,وی,انان,آنان,انها,آنها,ان,آن,این,كنيد,است,باشد,بكند,بود,بكنيد,بشود,دارد,داريد,داريم,آمد,آورد,آيد,آيند,باشند,باشيد,بخواهند,برود,بروند,بگيرند,بوديم,بيايد,توانست,توانند,داد,دانيم,خواهيد,ديد,شماريم,شويم,كرد,كرديد,كند,كنند,كنيم,كوچك,نداريم,نكرديد,نكند,نيامد,نيست,نيستيم,هست,هستند,محتاجيم,شود,کنيد,تركيب,هستيم,دود,دارم,ندارد,بگيريد,تبديل,فرموديد,بگيريم,برسد,بگيرد,بوديد,توانستيد,داديد,كنم,نباشيم,ببينيد,شد,آمدند,باشيم,ببينيم,بپذيريم,بتوانند,بتوانيم,بدهد,بدهند,بدهيم,بردارد,برسانيم,بشناسند,بفرمائيد,بكنند,بگوييد,بگوييم,دهد,تواند,گيرد,مي‏شود,آوردند,توانيم,پردازيم,اميدوارم,بينند,بينيد,توانيد,خوانيم,دانم,دانند,دهم,شناسند,فهمد,گوئيم,گويند,گوييم,نمايد,پذيرد,خواهد,نداشت,نبود,نيستند,داديم,بشناسد,رويم,بيند,گذاريد,گويد,ساخت,هر,گرچه,بنابراين,آنچه,آنكه,ابتداء,اينها,يعني,البته,چطور,با,چرا,که,چند,چون,چه,چي,يا,يك,ها,به,بر,آن,از,را,و,كه,براي,در,درباره,بعد,بلكه,تا,پس,آنگاه,اينجا,جلوتر,همان,آخر,الان,ديگر,امروز,هميشگي,هم,همه,همين,هيچ,همينگونه,وقتي,حداقل,منتها,ابتدا,توي,بعضي,بسيار,بي,لازم,مبادا,مكان,كسي,طرف,زمان,بايد,آيا,اين,شما,حالا,خودش,اينكه,ما,آنجا,اگر,زير,خود,فقط,خودشان,يک,من,آنها,خودمان,بنده,اما,او,ايشان,شناختن,آوردن,آمدن,كردن,بودن,است,بود,شد,شود,باشد,باید,شاید,هست,نیست,نبود,می,این,آن,آنجا,یک,حالا,دیگر,یعنی,یکی,دراین,درآن,بعدا,اش,هم,برای,کنیم,اگر,میشود,نپذیرفت,ندارد,ندارید,نداریم,نداند,نکرده,نیز,هستید,هستیم,همانطور,همه,هیچگونه,كرده,بوديد,اما,نباید,میتواند,میشود,ناظر,نمیتوانیم,نمیخواهیم,نمیخورد,نمیشویم,نمیگوییم,مي,حجت الاسلام,حجت الاسلام و المسلمین,حجةالاسلام و المسلمین,حجةالاسلام,والمسلمین,میکند,آیا,ایا,ايا,حجت الاسلام والمسلمین, پیدا ميکند,پیدا,پيدا,اقتضاء انشاء فعلیت" stopwords_fr_sr = "و،شده،از,در,به,را,که,چه,با,تا,بر,ما,شما,ایشان,من,تو,او,وی,انان,آنان,انها,آنها,ان,آن,این,كنيد,است,باشد,بكند,بود,بكنيد,بشود,دارد,داريد,داريم,آمد,آورد,آيد,آيند,باشند,باشيد,بخواهند,برود,بروند,بگيرند,بوديم,بيايد,توانست,توانند,داد,دانيم,خواهيد,ديد,شماريم,شويم,كرد,كرديد,كند,كنند,كنيم,كوچك,نداريم,نكرديد,نكند,نيامد,نيست,نيستيم,هست,هستند,محتاجيم,شود,کنيد,تركيب,هستيم,دود,دارم,ندارد,بگيريد,تبديل,فرموديد,بگيريم,برسد,بگيرد,بوديد,توانستيد,داديد,كنم,نباشيم,ببينيد,شد,آمدند,باشيم,ببينيم,بپذيريم,بتوانند,بتوانيم,بدهد,بدهند,بدهيم,بردارد,برسانيم,بشناسند,بفرمائيد,بكنند,بگوييد,بگوييم,دهد,تواند,گيرد,مي‏شود,آوردند,توانيم,پردازيم,اميدوارم,بينند,بينيد,توانيد,خوانيم,دانم,دانند,دهم,شناسند,فهمد,گوئيم,گويند,گوييم,نمايد,پذيرد,خواهد,نداشت,نبود,نيستند,داديم,بشناسد,رويم,بيند,گذاريد,گويد,ساخت,هر,گرچه,بنابراين,آنچه,آنكه,ابتداء,اينها,يعني,البته,چطور,با,چرا,که,چند,چون,چه,چي,يا,يك,ها,به,بر,آن,از,را,و,كه,براي,در,درباره,بعد,بلكه,تا,پس,آنگاه,اينجا,جلوتر,همان,آخر,الان,ديگر,امروز,هميشگي,هم,همه,همين,هيچ,همينگونه,وقتي,حداقل,منتها,ابتدا,توي,بعضي,بسيار,بي,لازم,مبادا,مكان,كسي,طرف,زمان,بايد,آيا,اين,شما,حالا,خودش,اينكه,ما,آنجا,اگر,زير,خود,فقط,خودشان,يک,من,آنها,خودمان,بنده,اما,او,ايشان,شناختن,آوردن,آمدن,كردن,بودن,است,بود,شد,شود,باشد,باید,شاید,هست,نیست,نبود,می,این,آن,آنجا,یک,حالا,دیگر,یعنی,یکی,دراین,درآن,بعدا,اش,هم,برای,کنیم,اگر,میشود,نپذیرفت,ندارد,ندارید,نداریم,نداند,نکرده,نیز,هستید,هستیم,همانطور,همه,هیچگونه,كرده,بوديد,اما,نباید,میتواند,میشود,ناظر,نمیتوانیم,نمیخواهیم,نمیخورد,نمیشویم,نمیگوییم,مي,حجت الاسلام,حجت الاسلام و المسلمین,حجةالاسلام و المسلمین,حجةالاسلام,والمسلمین,میکند,آیا,ایا,ايا,حجت الاسلام والمسلمین, پیدا ميکند,پیدا,پيدا,اقتضاء انشاء فعلیت"
stopwords_fr_ext = "ابی,ارش,است,الف,امی,ان,انجام,انرا,انکه,اول,ای,ب ,باو,برات,بردن,برنامه,بطور,بند,به,بوده,بیبی,بین,پ ,پنج,پنجم,ت ,تبصره,تلف,تمام,تواند,توجه,توسط,جرائم,چهار,حد,خواه,خواهند,داده,داشت,داشته,دم,ده,دو,دوم,دیگری,ذی,رد,رسیدگی,روز,روز ,سایر,سه,سوم,سی,شدن,شش,شود,شوند,صورت,صورتی,صورتیکه,عدم,علیه,عین,غیر,قانون,قانونی,قبل,قرار,قضایی,قوانین,کس,کل,کننده,که,گاه,گردد,ماده,ماده ,ماه,مثل,مقررات,مگر,مگر ,موارد,مواردی,مورد,می,میبرد,میتواند,میشود,میکند,میگردد,نباشد,نباشد ,نخواهد,نداشته,نشود,نصبت,نظر,نفر,نمایند,نمی,نمیشود,نیز,نیز ,های,وارد,وارده,واقع,ولی,وی,یکی" stopwords_fr_ext = "ابی,ارش,است,الف,امی,ان,انجام,انرا,انکه,اول,ای,ب ,باو,برات,بردن,برنامه,بطور,بند,به,بوده,بیبی,بین,پ ,پنج,پنجم,ت ,تبصره,تلف,تمام,تواند,توجه,توسط,جرائم,چهار,حد,خواه,خواهند,داده,داشت,داشته,دم,ده,دو,دوم,دیگری,ذی,رد,رسیدگی,روز,روز ,سایر,سه,سوم,سی,شدن,شش,شود,شوند,صورت,صورتی,صورتیکه,عدم,علیه,عین,غیر,قانون,قانونی,قبل,قرار,قضایی,قوانین,کس,کل,کننده,که,گاه,گردد,ماده,ماده ,ماه,مثل,مقررات,مگر,مگر ,موارد,مواردی,مورد,می,میبرد,میتواند,میشود,میکند,میگردد,نباشد,نباشد ,نخواهد,نداشته,نشود,نصبت,نظر,نفر,نمایند,نمی,نمیشود,نیز,نیز ,های,وارد,وارده,واقع,ولی,وی,یکی"
@@ -206,10 +210,13 @@ def extract_domain_words(
final_structure = {} final_structure = {}
all_code_labels = list(json_input_data.keys()) all_code_labels = list(json_input_data.keys())
# برای هر عنوان اصلی # برای هر عنوان اصلی
for code_label in all_code_labels: for code_label in all_code_labels:
if code_label == 'سایر':
continue
current_words_dict = json_input_data[code_label]
code_label = text_normalizer.normalize_qanon(code_label) code_label = text_normalizer.normalize_qanon(code_label)
if not code_label in dict_domain_id: if not code_label in dict_domain_id:
print( "------------ error ", item ) print( "------------ error ", item )
@@ -218,7 +225,6 @@ def extract_domain_words(
domain_id = dict_domain_id[code_label] domain_id = dict_domain_id[code_label]
code_label_id = domain_type + "_" + domain_id code_label_id = domain_type + "_" + domain_id
current_words_dict = json_input_data[code_label]
# 1. words_general — تمام کلمات این عنوان — مرتب بر اساس تکرار # 1. words_general — تمام کلمات این عنوان — مرتب بر اساس تکرار
@@ -266,15 +272,17 @@ def extract_domain_words(
list_code_words = [] list_code_words = []
for other_title in all_code_labels: for other_title in all_code_labels:
if other_title == code_label:
continue
other_words = set(json_input_data[other_title].keys()) other_words = set(json_input_data[other_title].keys())
current_words = set(current_words_dict.keys()) current_words = set(current_words_dict.keys())
other_title = text_normalizer.normalize_qanon(other_title) other_title = text_normalizer.normalize_qanon(other_title)
if not other_title in dict_domain_id :
if (other_title == code_label) or (other_title =='سایر'):
continue
if not (other_title in dict_domain_id):
print( "========================= error ", other_title ) print( "========================= error ", other_title )
continue continue
@@ -323,11 +331,15 @@ def extract_domain_words(
final_structure[code_label] = data final_structure[code_label] = data
eid = code_label_id eid = code_label_id
print(f'data Created! {eid}')
try: try:
resp = elastic.update_index_doc(True, index_name_o, eid, data) resp = elastic.update_index_doc(True, index_name_o, eid, data)
except Exception as e: except Exception as e:
pass import traceback
print(traceback.print_exc())
print(f'data NOT saved in es')
print(f'data saved in es')
# ذخیره خروجی نهایی # ذخیره خروجی نهایی
with open("./analyzed_domains.json", "w", encoding="utf-8") as f: with open("./analyzed_domains.json", "w", encoding="utf-8") as f:
@@ -338,19 +350,515 @@ def extract_domain_words(
########################################################################### ###########################################################################
def excel_to_json(excel_file, required_columns=None, sheet_name=0):
"""
خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری.
Args:
sheet_name: نام sheet (رشته) یا شماره آن (عدد). پیش‌فرض: 0 (اولین sheet)
"""
sheet_names = pd.ExcelFile(excel_file).sheet_names
print("all sheet")
for i, name in enumerate(sheet_names, start=1):
print(f" {i}. {name}")
df = pd.read_excel(excel_file, sheet_name=sheet_name)
if required_columns is None:
selected_columns = df.columns.tolist()
else:
missing = [col for col in required_columns if col not in df.columns]
if missing:
raise ValueError(f"ستون‌های مفقوده در sheet '{sheet_name}': {missing}")
selected_columns = required_columns
return df[selected_columns].to_dict(orient='records')
def update_history_code(data, index_name, elastic=None, sub_key='', qanon_name='' ):
from pydantic import BaseModel
from typing import List, Optional
# Base-Model
class DataHistoryIn(BaseModel):
id: str
content: str
path: str
qanon: str
reason: str
confidence: float
class DataHistoryOut(BaseModel):
label: str
score: float
version_key: str = 'llm_cg5m_v1'
sub_key: Optional[List[str]] = ['positve', 'negative']
description: str
version_key= "llm_cg5m_v1"
domain_type = "D51_v1"
text_normalizer = TextNormalizer()
with open("data/ai/domains_list.json", "r", encoding="utf-8") as file:
domains_list = json.load(file)
dict_domain_id = {}
labels_list = []
for item in domains_list[domain_type] :
item["domain_name"] = text_normalizer.normalize_qanon(item["domain_name"])
labels_list.append(item["domain_name"])
dict_domain_id[item["domain_name"]] = str(item["id"])
for i in data :
id = i['id']
res = elastic.get_doctument(index_name, id)
h_data = res['_source']['history_codes']
print(
'='*25,
f'before {type(h_data)} -> {h_data}',
F'id {id}',
sep='\n',
)
new_data = {
"label": text_normalizer.normalize_qanon(qanon_name), # normalize
"score": i['confidence'],
"sub_key": sub_key,
"description": i['reason'],
"version_key": version_key
}
h_data.append(new_data)
for qq in h_data:
if "description" not in qq.keys():
qq['description'] = ''
print(
'='*25,
f'after {type(h_data)} -> {h_data}',
F'id {id}',
sep='\n',
)
try:
resp = elastic.update_index_doc(True, index_name, id, h_data)
except Exception as e:
import traceback
print(traceback.print_exc())
print(f'data NOT saved in es')
break
def get_json_files(directory_path):
"""
دریافت لیست مسیرهای کامل تمام فایل‌های .json در یک دایرکتوری (فقط سطح اول).
Args:
directory_path (str یا Path): مسیر دایرکتوری
Returns:
list[Path]: لیستی از مسیرهای Path برای فایل‌های JSON
"""
dir_path = Path(directory_path)
if not dir_path.is_dir():
raise ValueError(f"مسیر داده شده یک دایرکتوری معتبر نیست: {directory_path}")
# جستجوی فایل‌های با پسوند .json (حساس به بزرگی/کوچکی نیست)
json_files = [f for f in dir_path.iterdir() if f.is_file() and f.suffix.lower() == '.json']
return json_files
def parse_json_tree(node):
# اگر node دیکشنری نیست، نادیده بگیر
if not isinstance(node, dict):
return {"title": "", "sections": []}
# استخراج title (اجباری)
title = node.get("title", "")
# استخراج sections (اگر نبود، لیست خالی)
raw_sections = node.get("sections", [])
# اگر raw_sections لیست نیست (مثلاً None یا غیر لیست)، تبدیل به لیست خالی
if not isinstance(raw_sections, list):
raw_sections = []
# پردازش بازگشتی زیربخش‌ها
cleaned_sections = []
for child in raw_sections:
cleaned_sections.append(parse_json_tree(child))
# if len(cleaned_sections)>0:
# return {
# "title": title,
# "sections": cleaned_sections
# }
# else:
# return {
# "title": title,
# }
return {
"title": title,
"sections": cleaned_sections
}
def run_misteral_translate(fr_text, client, _id):
try:
# 1) فراخوانی agent — مثال با متد "run"
# (اگر SDK تو متد دیگری داره، اون رو با اسم درست عوض کن)
# print('start')
resp = client.beta.conversations.start(
agent_id=_id,
inputs=[ {"role": "user", "content": fr_text} ]
# بعضی SDKها فقط input string می‌گیرن؛ اگر SDK تو فرق داره، با docs تطبیق بده
# inputs="Who is Albert Einstein?",
#store=False
)
finall = resp.outputs[0].content
finall = json.loads(finall)
# print(
# f'resp {type(finall)} -> {finall}'
# )
return {
fr_text: finall
}
except Exception as e:
# هندل کردن خطا
print(f"[ERROR] Failed for word '{fr_text}': {str(e)}")
return {
"word": fr_text,
"result": "model-failed",
"error": str(e)
}
def extract_titles(data):
"""
بازگشت یک لیست از تمام 'title' ها در ساختار nested
"""
titles = []
if isinstance(data, dict):
if 'title' in data:
titles.append(data['title'])
if 'sections' in data and isinstance(data['sections'], list):
for sec in data['sections']:
titles.extend(extract_titles(sec))
return titles
def process_all_json(all_json_paths, output_path):
from mistralai import Mistral
from mistralai import CompletionArgs, ResponseFormat, JSONSchema
from pydantic import BaseModel
from typing import List, Optional
import json
api_key = "0766TfYbm2KHOyBqUKXn7AnWy0G5U4fO"
instructions = """
Translate the provided French sentence into English and Persian.
- The translation must be accurate and natural, not word-for-word.
- Do not omit or add any information.
- Return the result strictly in JSON format matching the given schema.
"""
class TranslateFrPerEN(BaseModel):
french: str
english: str
persian: str
model = "mistral-large-latest"
client = Mistral(api_key=api_key)
translate_agent = client.beta.agents.create(
model=model,
name="translater",
description="Translate the given sentences from French to English and Persian",
instructions=instructions,
completion_args=CompletionArgs(
response_format=ResponseFormat(
type="json_schema",
json_schema=JSONSchema(
name="pro_word_schema", schema=TranslateFrPerEN.model_json_schema()
),
)
),
)
load_dotenv(dotenv_path='config.env') # مجموعه‌ای برای ذخیره‌ی تمام عناوین بدون تکرار
all_titles = set()
# 1. جمع کردن تمام عناوین از همه فایل‌ها
for j_file in all_json_paths:
with open(j_file, "rb") as f:
data = orjson.loads(f.read())
titles = extract_titles(data)
all_titles.update(titles)
print(f"Total unique titles found: {len(all_titles)}")
temp = r'D:\init_mahdi\project\dataParsers\data\FLC\cleaned\temp.json'
with open(temp, "rb") as f:
temp_data = orjson.loads(f.read())
print(f'temp_data orjson {len(temp_data)}')
temp_titles = set()
for item in temp_data:
if isinstance(item, dict) and item: # اگر دیکشنری ناتهی باشد
title = next(iter(item.keys())) # اولین (و تنها) کلید دیکشنری
temp_titles.add(title)
# حالا می‌توانیم تفریق کنیم
print(f'temp_data {len(temp_titles)}')
print(f'before all_titles {len(all_titles)}')
all_titles -= temp_titles
print(f'now all_titles {len(all_titles)}')
for i, title in enumerate(all_titles, start=1):
print(f'--- {i}/{len(all_titles)}')
transelated = run_misteral_translate(fr_text=title,client=client,_id=translate_agent.id )
# print(
# f'transelated {transelated}'
# )
with open(temp, "ab") as f:
f.write(orjson.dumps(transelated, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS))
# 3. ساختار خروجی نهایی
final_result = {
transelated
}
# 4. ذخیره در یک فایل JSON
output_file = r'D:\init_mahdi\project\dataParsers\data\FLC\cleaned\all_titles_translated.json'
with open(output_file, "wb") as f:
f.write(orjson.dumps(final_result, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS))
print(f"All translations saved to {output_file}")
def save_to_excel(json_data, output_dir , output_file_name):
import orjson
import hashlib
from openpyxl import Workbook
import os
# -----------------------------
# تابع بارگذاری دیکشنری ترجمه (یک‌بار اجرا می‌شه)
# -----------------------------
def load_translation_dict():
_json_path1 = r'D:\init_mahdi\project\dataParsers\data\FLC\cleaned\all_titles_translated.json'
with open(_json_path1, "rb") as f:
_TRANSLATE_DICT = orjson.loads(f.read())
print(f'---- TRANSLATE_DICT {len(_TRANSLATE_DICT)} ----')
result = {}
for item in _TRANSLATE_DICT:
if isinstance(item, dict) and len(item) == 1:
key = next(iter(item)) # گرفتن تنها کلید دیکشنری
value = item[key]
key =key.strip()
result[key] = value
else:
raise ValueError(f"Invalid item format: {item}")
return result
# return _TRANSLATE_DICT
def do_translation(fr_text, translate_dict):
# print(f'fr_text {fr_text}')
key = fr_text.strip()
if key in translate_dict:
# print(
# f'key {type(key)} -> {key}'
# )
entry = translate_dict[key]
en = entry.get("english", key)
fa = entry.get("persian", key)
# print(f'en {en}, fa {fa}')
return en, fa
else:
print(f'fr, {key}')
# اگر ترجمه نبود، همان متن فرانسوی استفاده شود
return key, key
# -----------------------------
# تابع جدید flatten_structure
# -----------------------------
def flatten_structure_with_translation(data, current_path_fr=None, all_rows_fr=None):
"""
Recursively collects all full paths (leaf paths) in French.
Returns list of lists: each inner list is a full path in French.
"""
if current_path_fr is None:
current_path_fr = []
if all_rows_fr is None:
all_rows_fr = []
title_fr = data.get("title", "").strip()
current_path_fr.append(title_fr)
sections = data.get("sections", [])
if not sections:
# Leaf: save full French path
all_rows_fr.append(current_path_fr.copy())
else:
for section in sections:
flatten_structure_with_translation(section, current_path_fr, all_rows_fr)
current_path_fr.pop()
return all_rows_fr
# -----------------------------
# تابع تولید ID یکتا برای یک مسیر
# -----------------------------
def generate_row_id(french_path, const_prefix="FR_LEGAL_"):
# تبدیل مسیر به یک رشته یکتا (مثلاً با جداکننده |)
path_str = "|".join(french_path)
hash_hex = hashlib.md5(path_str.encode('utf-8')).hexdigest()[:12] # 12 کاراکتر کافیه
return const_prefix + hash_hex
# -----------------------------
# تابع نوشتن فایل اکسل برای یک زبان
# -----------------------------
def write_excel_file(rows_with_ids, filename, lang, output_dir="output"):
os.makedirs(output_dir, exist_ok=True)
filename = os.path.join(output_dir, f"{filename}_{lang}.xlsx")
wb = Workbook()
ws = wb.active
ws.title = f"Structure ({lang.upper()})"
# عنوان ستون‌ها: ID و سپس Level 1, Level 2, ...
max_cols = max(len(row) for row in rows_with_ids) if rows_with_ids else 1
headers = ["ID"] + [f"Level_{i+1}" for i in range(max_cols - 1)]
ws.append(headers)
for row_id, titles in rows_with_ids:
ws.append([row_id] + titles)
# تنظیم عرض ستون‌ها
for col in ws.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if cell.value and len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 60)
ws.column_dimensions[column].width = adjusted_width
wb.save(filename)
print(f"✅ Saved {lang} file: {filename}")
# -----------------------------
# تابع اصلی پردازش
# -----------------------------
def process_json_to_multilingual_excel(json_data, filename, output_dir="output"):
# مرحله ۱: استخراج تمام مسیرهای فرانسوی (leaf paths)
french_paths = flatten_structure_with_translation(json_data)
translate_dict = load_translation_dict()
# مرحله ۲: برای هر مسیر، ترجمه‌های انگلیسی و فارسی را بساز
rows_fr = []
rows_en = []
rows_fa = []
for i, fr_path in enumerate(french_paths,start=1):
# تولید ID یکتا بر اساس مسیر فرانسوی
f_row_id = generate_row_id(fr_path, const_prefix=f'{filename[-11:-1]}_FRC{i}_')
e_row_id = generate_row_id(fr_path, const_prefix=f'{filename[-11:-1]}_ENG{i}_')
p_row_id = generate_row_id(fr_path, const_prefix=f'{filename[-11:-1]}_PER{i}_')
# ترجمه هر عنوان در مسیر
en_path = []
fa_path = []
for title_fr in fr_path:
en, fa = do_translation(title_fr, translate_dict)
en_path.append(en)
fa_path.append(fa)
rows_fr.append((f_row_id, fr_path))
rows_en.append((e_row_id, en_path))
rows_fa.append((p_row_id, fa_path))
# مرحله ۳: ذخیره سه فایل جداگانه
write_excel_file(rows_fr, filename, "french", output_dir)
write_excel_file(rows_en, filename, "english", output_dir)
write_excel_file(rows_fa, filename, "persian", output_dir)
process_json_to_multilingual_excel(json_data, output_file_name, output_dir)
##################################################################################
# trsanslate all the francais excel to english and persian
##################################################################################
# # base_path = r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\France Legal Codes\code_structures'
# in_path= r'D:\init_mahdi\project\dataParsers\data\ai\France Legal Codes\cleaned_phase1'
# output_path= r'D:\init_mahdi\project\dataParsers\data\ai\France Legal Codes\cleaned_phase2'
# o_path= r'D:\init_mahdi\project\dataParsers\data\FLC\cleaned'
# all_json = get_json_files(in_path)
# for i, json_ in enumerate(all_json, start=1):
# print(f'--- {i}/{len(all_json)} ---')
# with open(json_, "rb") as f:
# json_file = orjson.loads(f.read())
# file_name= os.path.basename(json_).replace('.json','')
# print(f'file_name {type(file_name)}')
# outpath = r'D:\init_mahdi\project\dataParsers\data\FLC\cleaned\excel'
# # resutl = save_to_excel(json_file, outpath)
# save_to_excel(
# json_data=json_file, output_file_name=file_name, output_dir=outpath
# )
#######################################################################################################
# exel_path1 = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\insurance_result_score.xlsx"
# qanon_name1 = 'بیمـه‌'
# # p sheet insurance
# # n sheet Non_insurance
# # exel2_path = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\international_trade_result_4.xlsx"
# # p sheet International_Trade
# # n sheet Non_International_Trade
# exel_path3 = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\water_result.xlsx"
# qanon_name3 = 'آب'
# # p sheet water
# # n sheet Non_water
# load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_113') # host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS') # password=os.getenv('HOST_113_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/" # path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map) # elastic = ElasticHelper(host, password, "elastic", path_base_map)
# # positve
# # negative
# result = excel_to_json(excel_file=exel_path1, sheet_name='insurance')
# result_f = update_history_code(data=result,elastic=elastic,index_name='mj_qa_section', sub_key='positve', qanon_name=qanon_name1)
# o1= r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\test1_excel.json'
# with open(o1, "w", encoding="utf-8") as f:
# json.dump(result, f, ensure_ascii=False, indent=2)
# final_domain_words = extract_domain_words(r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\bank_words_per\data\corrected_sorted1.json", elastic, "mj_qa_domain")
# # final_domain_words = extract_domain_words("data/ai/corrected_sorted1.json", elastic, "mj_qa_doamin")
# # python -m app.for_ai.codes_tokens
final_domain_words = extract_domain_words("data/ai/corrected_sorted1.json", elastic, "mj_qa_doamin")
+8
View File
@@ -0,0 +1,8 @@
file_path = r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\FLC\cleaned\temp.json'
with open(file_path, "r", encoding="utf-8") as f:
text = f.read()
import re
matches = re.findall(r'persian', text)
print("تعداد دقیق:", len(matches))
+2
View File
@@ -5,3 +5,5 @@ bs4
elasticsearch elasticsearch
pandas pandas
openpyxl openpyxl
mistralai
orjson