BU1
This commit is contained in:
+1
-1
@@ -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
|
||||
|
||||
+1
-1
@@ -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 = []
|
||||
|
||||
+175
-10
@@ -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):
|
||||
@@ -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)
|
||||
@@ -189,13 +209,162 @@ def count_tokens(model_name, system_prompt, user_prompt):
|
||||
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(
|
||||
@@ -289,7 +458,6 @@ if __name__ == "__main__":
|
||||
# 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, ...)
|
||||
@@ -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",
|
||||
@@ -508,7 +674,6 @@ if __name__ == "__main__":
|
||||
# data=error_data
|
||||
# )
|
||||
|
||||
|
||||
##########################################################################
|
||||
print(":D")
|
||||
# python3 -m aiDataParser.core.data_normalizer
|
||||
Reference in New Issue
Block a user