diff --git a/__init__.py b/__init__.py index 9d83305..d5961d8 100644 --- a/__init__.py +++ b/__init__.py @@ -1,3 +1,3 @@ -from aiDataParser.core.ai_parser import AsyncCore +from aiDataParser.core.ai_parser import AsyncCore, SmartMultiServerCore from aiDataParser.core.ai_stream_parser import StreamAsyncCore from aiDataParser.core.data_normalizer import load_orjson, save_orjson diff --git a/core/ai_parser.py b/core/ai_parser.py index 72f6c1b..cdfd8bf 100644 --- a/core/ai_parser.py +++ b/core/ai_parser.py @@ -1392,7 +1392,7 @@ class SmartMultiServerCore: print(f"=== Config{i}: {j}") else: - print(f"Not Found Any Active Service !!!") + raise ValueError(f"Not Found Any Active Service !!!") def validate_configs(self): self.active_configs = [] diff --git a/core/data_normalizer.py b/core/data_normalizer.py index 2a4c6ea..02c7d6f 100644 --- a/core/data_normalizer.py +++ b/core/data_normalizer.py @@ -3,6 +3,26 @@ import json import orjson import tiktoken from pathlib import Path +from typing import List, Dict, Optional, Union, Tuple +from pydantic import BaseModel, ConfigDict, ValidationError + + +class LLMOutputData(BaseModel): + id: str + + # این تنظیم باعث می‌شود هر فیلد دیگری که در JSON هست حفظ شود و از بین نرود + model_config = ConfigDict(extra="allow") + + def __hash__(self): + # تولید هش فقط بر اساس فیلد id + return hash(self.id) + + def __eq__(self, other): + # برای اینکه Set پایتون متوجه شود دو شیء تکراری هستند، + # باید به آن بگوییم که برابری دو شیء به معنای برابری id آن‌هاست. + if isinstance(other, LLMOutputData): + return self.id == other.id + return False def load_orjson(path: str | Path): @@ -47,7 +67,7 @@ def merge_json_dir(input_path, output_path): item_id = item.get("id") if not item_id: item_id = item.get("_id") - + if item_id is None: # اگر id نداشت، می‌تونی تصمیم بگیری: نگه داری یا ردش کنی # اینجا فرض می‌کنیم فقط مواردی با id معتبر مهم هستند @@ -156,9 +176,7 @@ def make_format(in_path, out_path): save_orjson(data=f_data, path=out_path) - def count_tokens(model_name, system_prompt, user_prompt): - """ شمارش دقیق توکن‌های ورودی برای مدل‌های مختلف """ @@ -173,6 +191,7 @@ def count_tokens(model_name, system_prompt, user_prompt): elif "gemma" in model_name.lower(): from transformers import AutoTokenizer + # SentencePiece tokenizer (Gemma از HuggingFace) tokenizer = AutoTokenizer.from_pretrained(model_name) tokens = tokenizer.encode(text) @@ -180,6 +199,7 @@ def count_tokens(model_name, system_prompt, user_prompt): elif "magistral" in model_name.lower() or "mistral" in model_name.lower(): from transformers import AutoTokenizer + # Mistral / Magistral tokenizer (BPE) tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) tokens = tokenizer.encode(text) @@ -187,15 +207,164 @@ def count_tokens(model_name, system_prompt, user_prompt): else: raise ValueError(f"Model {model_name} not recognized.") - + + +def validate_merge_json_dir( + input_path, + base_output_path, + final_data_name, + processed_id_name, +): + output_data_path = base_output_path / final_data_name + processed_id_path = base_output_path / processed_id_name + directory = Path(input_path) + + if not directory.is_dir(): + raise ValueError(f"Not valid PATH: {input_path}") + + # این متغیر (Set) تمام داده‌های یکتا را به صورت شیء (Object) در خود نگه می‌دارد + unique_objects_set = set() + + # مرحله ۱: خواندن داده‌های قبلی از خروجی نهایی (برای تست و جلوگیری از تکرار با داده‌های قدیمی) + try: + existing_data = load_orjson(output_data_path) + if isinstance(existing_data, list): + for item in existing_data: + if "id" not in item or item["id"] is None: + continue + try: + # سریالایز با Pydantic + obj = LLMOutputData(**item) + # اضافه کردن به Set. اگر id تکراری باشد، پایتون اتوماتیک نادیده می‌گیرد + unique_objects_set.add(obj) + except ValidationError as e: + print( + f"⚠️ Validation error in existing data (ID: {item.get('id')}): {e}" + ) + print(f"✅ Loaded {len(unique_objects_set)} unique items from existing output.") + except Exception: + print("ℹ️ No valid existing output data found. Starting fresh.") + + # مرحله ۲: خواندن فایل‌های جدید دایرکتوری Temp + failed_files = 0 + json_files = list(directory.glob("*.json")) + + if not json_files: + print("⚠️ NO JSON File Found In This PATH") + # حتی اگر فایل جدیدی نبود، ممکن است بخواهیم داده‌های قبلی که تمیز شده‌اند را دوباره ذخیره کنیم + else: + for json_file in json_files: + try: + data = load_orjson(json_file) + if not data: # خالی یا None + failed_files += 1 + continue + + if ( + isinstance(data, list) + and len(data) > 0 + and isinstance(data[0], dict) + ): + for item in data: + if "id" not in item or item["id"] is None: + continue + + try: + # سریالایز داده جدید + obj = LLMOutputData(**item) + # افزودن به Set. (بررسی تکراری بودن فقط با id در کسری از ثانیه انجام می‌شود) + unique_objects_set.add(obj) + except ValidationError as e: + print(f"⚠️ Validation error in file {json_file.name}: {e}") + else: + raise ValueError(f"no list available in this json -> {json_file}") + + except ( + json.JSONDecodeError, + ValueError, + OSError, + KeyError, + TypeError, + ) as e: + print(f"❌ Failed in process '{json_file.name}' ") + failed_files += 1 + + print(f"Total unique_data ready to save: {len(unique_objects_set)}") + + # مرحله ۳: ساخت داینامیک داده‌های خروجی و لیست idهای پردازش شده + # تبدیل دوباره اشیاء به دیکشنری (فیلدهای اضافه با این متد حفظ می‌شوند) + final_unique_data = [obj.model_dump() for obj in unique_objects_set] + + # ساخت داینامیک لیست IDها از روی Set + dynamic_seen_ids = [obj.id for obj in unique_objects_set] + + # مرحله ۴: ذخیره‌سازی داده‌ها + try: + save_orjson(data=final_unique_data, path=output_data_path) + save_orjson(data=dynamic_seen_ids, path=processed_id_path) + return len(final_unique_data), len(dynamic_seen_ids) + except Exception as e: + print(f"❌ Error in saving final file: {e}") + return 0, 0 + # --- نحوه استفاده --- +# python3 /home1/ava3/init_mahdi/project/aiDataParser/core/data_normalizer.py if __name__ == "__main__": - # ##### یکی کردن تمام بچ های خروجی در یک فایل - merge_json_dir( - input_path= '/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_6152/batch_data', - output_path='/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_6152/final_data_subject_unity.json' + # ##### یکی کردن تمام بچ های خروجی در یک فایل و ساخت proccessed_id + [ + 1, + 2, + 3, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 30, + 32, + 33, + 34, + 35, + ] + i = 2 + # validate_merge_json_dir( + # input_path=Path( + # f"/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_all_qavanin/part_{i}/batch_data" + # ), + # base_output_path=Path( + # f"/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_all_qavanin/part_{i}" + # ), + # final_data_name="final_data_subject_unity.json", + # processed_id_name="processed_id.json", + # ) + print( + len( + load_orjson( + "/home1/ava3/init_mahdi/project/rule_extractor/im_based/data/sequential/subject_unity/output_all_qavanin/part_1/final_data_subject_unity.json" + ) + ) ) + # # ##### یکی کردن تمام بچ های خروجی در یک فایل + # merge_json_dir( + # input_path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_heading/output1/batch_data", + # output_path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_heading/output1/final_data_gemma-27.json", + # ) ###### ساخت یک proccessed id از فایل نهایی # make_new_proccessed_ids_from_file( @@ -270,7 +439,7 @@ if __name__ == "__main__": ##################################### work with tree ##################################### # fr_tree = '/home1/ava3/project/aiDataParser/task/match_code_fr_per/prompt_ir_def.json' # fr_tree = load_orjson(fr_tree) - + # code_title = [] # for k, v in fr_tree.items(): # code_title.append( @@ -278,18 +447,17 @@ if __name__ == "__main__": # ) # save_orjson( - # data=code_title, + # data=code_title, # path='/home1/ava3/project/aiDataParser/task/match_code_fr_per/all_code_title_persian.json' # ) ##################################### make tree ##################################### # fr_tree = '/home1/ava3/franc_legal_codes/translate/all_tree_franc.json' # fr_tree = load_orjson(fr_tree) - + # pr_data = '/home1/ava3/project/aiDataParser/task/france_translate/all_pr_fr_title_cleaned_1.json' # pr_data = load_orjson(pr_data) - # def build_lookup(flat_list): # lookup = {} # for item in flat_list: @@ -298,7 +466,6 @@ if __name__ == "__main__": # lookup[key] = item # return lookup - # def clean_title(title: str) -> str: # import re # title = re.sub(r'\n+', '', title) # \s+ = هر ترکیبی از whitespace (space, \t, \n, \r, ...) @@ -316,12 +483,12 @@ if __name__ == "__main__": # persian = enriched.get("persian") # if persian == None: # unlist = { - # 'fr_title':title, + # 'fr_title':title, # 'pr_title':enriched.get('france') # } # print(unlist) # return (unlist, 1) - # # ساخت گره جدید + # # ساخت گره جدید # new_node = { # "france": title, # "persian": enriched.get("persian"), # پیش‌فرض: همان فرانسوی اگر ترجمه نبود @@ -351,7 +518,7 @@ if __name__ == "__main__": # ) # save_orjson( - # path='/home1/ava3/project/aiDataParser/task/france_translate/tree_test1_title.json', + # path='/home1/ava3/project/aiDataParser/task/france_translate/tree_test1_title.json', # data=f_data # ) @@ -368,11 +535,11 @@ if __name__ == "__main__": # if '.' in title: # title = title.replace('.', '') - + # if ':' in title: # title = title.split(':', 1)[1].strip() - - # if ')' in title : #and '(' not in title: + + # if ')' in title : #and '(' not in title: # colon_count1 = title.count(')') # colon_count2 = title.count('(') # if colon_count1 == colon_count2: @@ -384,7 +551,7 @@ if __name__ == "__main__": # title = title.split(')', 1)[1].strip() # # print(title) # # break - # i['persian'] = title + # i['persian'] = title # save_orjson( # data=input_per, @@ -399,11 +566,11 @@ if __name__ == "__main__": # # if len(i['persian']) > 0 and isinstance(i['persian'], list) and bool(i['persian'][0] != None) and bool(i['persian'][0] != ''): # data_1.append( # { - # "id": str(i["id"]), - # # "ai_code_version": str(i["ai_code_version"]), + # "id": str(i["id"]), + # # "ai_code_version": str(i["ai_code_version"]), # 'persian' : i['fa'] # } - # ) + # ) # # else: # # unvalid.append(str(i["id"])) @@ -413,7 +580,7 @@ if __name__ == "__main__": # { # "id": str(i["id"]), # "fr": str(i["fr"]) - # } + # } # for i in data_2 # if str(i['id']) in unvalid # ] @@ -436,7 +603,6 @@ if __name__ == "__main__": # ) # break - # save_orjson( # data=f_data, # path="/home1/ava3/project/aiDataParser/task/france_translate/all_title_persian/temp2.json", @@ -500,15 +666,14 @@ if __name__ == "__main__": # ) # save_orjson( - # path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/finall_dataset.json', + # path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/finall_dataset.json', # data=clean_data - # ) + # ) # save_orjson( - # path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/error_data.json', + # path='/home1/ava3/project/aiDataParser/task/keyword_extractor/output/error_data.json', # data=error_data - # ) - + # ) ########################################################################## print(":D") -# python3 -m aiDataParser.core.data_normalizer \ No newline at end of file +# python3 -m aiDataParser.core.data_normalizer