diff --git a/app/for_ai/codes_tokens.py b/app/for_ai/codes_tokens.py index 4504840..f6539da 100644 --- a/app/for_ai/codes_tokens.py +++ b/app/for_ai/codes_tokens.py @@ -9,6 +9,7 @@ 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_ext = "ابی,ارش,است,الف,امی,ان,انجام,انرا,انکه,اول,ای,ب ,باو,برات,بردن,برنامه,بطور,بند,به,بوده,بیبی,بین,پ ,پنج,پنجم,ت ,تبصره,تلف,تمام,تواند,توجه,توسط,جرائم,چهار,حد,خواه,خواهند,داده,داشت,داشته,دم,ده,دو,دوم,دیگری,ذی,رد,رسیدگی,روز,روز ,سایر,سه,سوم,سی,شدن,شش,شود,شوند,صورت,صورتی,صورتیکه,عدم,علیه,عین,غیر,قانون,قانونی,قبل,قرار,قضایی,قوانین,کس,کل,کننده,که,گاه,گردد,ماده,ماده ,ماه,مثل,مقررات,مگر,مگر ,موارد,مواردی,مورد,می,میبرد,میتواند,میشود,میکند,میگردد,نباشد,نباشد ,نخواهد,نداشته,نشود,نصبت,نظر,نفر,نمایند,نمی,نمیشود,نیز,نیز ,های,وارد,وارده,واقع,ولی,وی,یکی" @@ -348,6 +349,7 @@ def extract_domain_words( return final_structure ########################################################################### + def excel_to_json(excel_file, required_columns=None, sheet_name=0): """ خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری. @@ -372,7 +374,8 @@ def excel_to_json(excel_file, required_columns=None, sheet_name=0): 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 @@ -444,7 +447,6 @@ def update_history_code(data, index_name, elastic=None, sub_key='', qanon_name=' break - def get_json_files(directory_path): """ دریافت لیست مسیرهای کامل تمام فایل‌های .json در یک دایرکتوری (فقط سطح اول). @@ -498,7 +500,8 @@ def parse_json_tree(node): "title": title, "sections": cleaned_sections } - + + def run_misteral_translate(fr_text, client, _id): try: @@ -531,6 +534,7 @@ def run_misteral_translate(fr_text, client, _id): "error": str(e) } + def extract_titles(data): """ بازگشت یک لیست از تمام 'title' ها در ساختار nested @@ -543,9 +547,7 @@ def extract_titles(data): for sec in data['sections']: titles.extend(extract_titles(sec)) return titles - - - + def process_all_json(all_json_paths, output_path): @@ -586,6 +588,8 @@ def process_all_json(all_json_paths, output_path): ), ) + + # مجموعه‌ای برای ذخیره‌ی تمام عناوین بدون تکرار all_titles = set() @@ -598,14 +602,34 @@ def process_all_json(all_json_paths, output_path): print(f"Total unique titles found: {len(all_titles)}") - temp = r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\FLC\cleaned\temp.json' - # 2. ترجمه همه عناوین - for title in 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}' - ) + # 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. ساختار خروجی نهایی @@ -614,25 +638,191 @@ def process_all_json(all_json_paths, output_path): } # 4. ذخیره در یک فایل JSON - output_file = r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\FLC\cleaned\all_titles_translated.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(): pass +def save_to_excel(json_data, output_dir , output_file_name): + import orjson + import hashlib + from openpyxl import Workbook + import os + + # ----------------------------- + # تابع بارگذاری دیکشنری ترجمه (یک‌بار اجرا می‌شه) + # ----------------------------- -# base_path = r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\France Legal Codes\code_structures' -in_path= r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\France Legal Codes\cleaned_phase1' -output_path= r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\France Legal Codes\cleaned_phase2' -o_path= r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\FLC\cleaned' + 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 -all_json = get_json_files(in_path) -process_all_json(all_json, o_path) - # for i in all_json: - + 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 = 'بیمـه‌' diff --git a/app/for_ai/testiii.py b/app/for_ai/testiii.py new file mode 100644 index 0000000..eb594d3 --- /dev/null +++ b/app/for_ai/testiii.py @@ -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)) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 3321bce..b62e988 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ bs4 elasticsearch pandas openpyxl +mistralai orjson \ No newline at end of file