translate fr to per & ar
This commit is contained in:
+317
-9
@@ -1,11 +1,14 @@
|
||||
import io
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from collections import defaultdict
|
||||
from dotenv import load_dotenv
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
|
||||
import pandas as pd
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
stopwords_fr_sr = "و،شده،از,در,به,را,که,چه,با,تا,بر,ما,شما,ایشان,من,تو,او,وی,انان,آنان,انها,آنها,ان,آن,این,كنيد,است,باشد,بكند,بود,بكنيد,بشود,دارد,داريد,داريم,آمد,آورد,آيد,آيند,باشند,باشيد,بخواهند,برود,بروند,بگيرند,بوديم,بيايد,توانست,توانند,داد,دانيم,خواهيد,ديد,شماريم,شويم,كرد,كرديد,كند,كنند,كنيم,كوچك,نداريم,نكرديد,نكند,نيامد,نيست,نيستيم,هست,هستند,محتاجيم,شود,کنيد,تركيب,هستيم,دود,دارم,ندارد,بگيريد,تبديل,فرموديد,بگيريم,برسد,بگيرد,بوديد,توانستيد,داديد,كنم,نباشيم,ببينيد,شد,آمدند,باشيم,ببينيم,بپذيريم,بتوانند,بتوانيم,بدهد,بدهند,بدهيم,بردارد,برسانيم,بشناسند,بفرمائيد,بكنند,بگوييد,بگوييم,دهد,تواند,گيرد,ميشود,آوردند,توانيم,پردازيم,اميدوارم,بينند,بينيد,توانيد,خوانيم,دانم,دانند,دهم,شناسند,فهمد,گوئيم,گويند,گوييم,نمايد,پذيرد,خواهد,نداشت,نبود,نيستند,داديم,بشناسد,رويم,بيند,گذاريد,گويد,ساخت,هر,گرچه,بنابراين,آنچه,آنكه,ابتداء,اينها,يعني,البته,چطور,با,چرا,که,چند,چون,چه,چي,يا,يك,ها,به,بر,آن,از,را,و,كه,براي,در,درباره,بعد,بلكه,تا,پس,آنگاه,اينجا,جلوتر,همان,آخر,الان,ديگر,امروز,هميشگي,هم,همه,همين,هيچ,همينگونه,وقتي,حداقل,منتها,ابتدا,توي,بعضي,بسيار,بي,لازم,مبادا,مكان,كسي,طرف,زمان,بايد,آيا,اين,شما,حالا,خودش,اينكه,ما,آنجا,اگر,زير,خود,فقط,خودشان,يک,من,آنها,خودمان,بنده,اما,او,ايشان,شناختن,آوردن,آمدن,كردن,بودن,است,بود,شد,شود,باشد,باید,شاید,هست,نیست,نبود,می,این,آن,آنجا,یک,حالا,دیگر,یعنی,یکی,دراین,درآن,بعدا,اش,هم,برای,کنیم,اگر,میشود,نپذیرفت,ندارد,ندارید,نداریم,نداند,نکرده,نیز,هستید,هستیم,همانطور,همه,هیچگونه,كرده,بوديد,اما,نباید,میتواند,میشود,ناظر,نمیتوانیم,نمیخواهیم,نمیخورد,نمیشویم,نمیگوییم,مي,حجت الاسلام,حجت الاسلام و المسلمین,حجةالاسلام و المسلمین,حجةالاسلام,والمسلمین,میکند,آیا,ایا,ايا,حجت الاسلام والمسلمین, پیدا ميکند,پیدا,پيدا,اقتضاء انشاء فعلیت"
|
||||
stopwords_fr_ext = "ابی,ارش,است,الف,امی,ان,انجام,انرا,انکه,اول,ای,ب ,باو,برات,بردن,برنامه,بطور,بند,به,بوده,بیبی,بین,پ ,پنج,پنجم,ت ,تبصره,تلف,تمام,تواند,توجه,توسط,جرائم,چهار,حد,خواه,خواهند,داده,داشت,داشته,دم,ده,دو,دوم,دیگری,ذی,رد,رسیدگی,روز,روز ,سایر,سه,سوم,سی,شدن,شش,شود,شوند,صورت,صورتی,صورتیکه,عدم,علیه,عین,غیر,قانون,قانونی,قبل,قرار,قضایی,قوانین,کس,کل,کننده,که,گاه,گردد,ماده,ماده ,ماه,مثل,مقررات,مگر,مگر ,موارد,مواردی,مورد,می,میبرد,میتواند,میشود,میکند,میگردد,نباشد,نباشد ,نخواهد,نداشته,نشود,نصبت,نظر,نفر,نمایند,نمی,نمیشود,نیز,نیز ,های,وارد,وارده,واقع,ولی,وی,یکی"
|
||||
@@ -345,22 +348,327 @@ def extract_domain_words(
|
||||
return final_structure
|
||||
###########################################################################
|
||||
|
||||
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
|
||||
|
||||
|
||||
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
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()
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
# مجموعهای برای ذخیرهی تمام عناوین بدون تکرار
|
||||
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'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\FLC\cleaned\temp.json'
|
||||
# 2. ترجمه همه عناوین
|
||||
for title in 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'C:\Users\TAVASI-3\Desktop\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
|
||||
|
||||
|
||||
# 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'
|
||||
|
||||
all_json = get_json_files(in_path)
|
||||
process_all_json(all_json, o_path)
|
||||
# for i in all_json:
|
||||
|
||||
#######################################################################################################
|
||||
# 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')
|
||||
# password=os.getenv('HOST_113_PASS')
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
# path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
# 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(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
|
||||
|
||||
@@ -5,3 +5,4 @@ bs4
|
||||
elasticsearch
|
||||
pandas
|
||||
openpyxl
|
||||
orjson
|
||||
Reference in New Issue
Block a user