394 lines
12 KiB
Python
Executable File
394 lines
12 KiB
Python
Executable File
from pydantic import BaseModel
|
|
from typing import List, Optional
|
|
from pathlib import Path
|
|
import os
|
|
import orjson
|
|
import time
|
|
import asyncio
|
|
from openai import OpenAI
|
|
import re
|
|
from functools import partial
|
|
from concurrent.futures import ProcessPoolExecutor
|
|
import multiprocessing
|
|
import json
|
|
# -------------------------- func
|
|
from openai import AsyncOpenAI
|
|
|
|
|
|
def get_max_number_file(directory):
|
|
# Pattern to match filenames like out_1.json, out_25.json, etc.
|
|
pattern = re.compile(r"output_(\d+)\.json$")
|
|
|
|
max_num = 0
|
|
|
|
for filename in os.listdir(directory):
|
|
match = pattern.match(filename)
|
|
if match:
|
|
num = int(match.group(1))
|
|
if num > max_num:
|
|
max_num = num
|
|
return max_num + 1
|
|
|
|
|
|
def load_orjson(path: str | Path):
|
|
path = Path(path)
|
|
with path.open("rb") as f: # باید باینری باز بشه برای orjson
|
|
return orjson.loads(f.read())
|
|
|
|
|
|
def save_orjson(path, data):
|
|
with open(path, "wb") as f:
|
|
f.write(
|
|
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
|
|
)
|
|
|
|
|
|
def assign_unique_ids(words):
|
|
total = len(words)
|
|
ids = (
|
|
f"{i:010d}" for i in range(1, total + 1)
|
|
) # generator for zero-padded 10-digit numbers
|
|
return [{"word": word, "id": id} for word, id in zip(words, ids)]
|
|
|
|
|
|
def single_worker_process(
|
|
llm_url,
|
|
base_dir,
|
|
data_batch,
|
|
model_name,
|
|
output_schema,
|
|
temperature,
|
|
top_p,
|
|
reasoning_effort,
|
|
max_token,
|
|
batch_file_name,
|
|
):
|
|
|
|
async def worker_loop():
|
|
final_output = []
|
|
processed_id = []
|
|
|
|
# ✅ کلاینت را داخل context async ایجاد کن
|
|
async with AsyncOpenAI(base_url=llm_url, api_key="EMPTY") as client:
|
|
|
|
async def process_item(item):
|
|
try:
|
|
messages = [
|
|
{"role": "system", "content": item.get("system_prompt", "")},
|
|
{"role": "user", "content": item.get("user_prompt", "")},
|
|
]
|
|
if item.get("assistant_prompt"):
|
|
messages.append(
|
|
{"role": "assistant", "content": item["assistant_prompt"]}
|
|
)
|
|
|
|
response = await client.chat.completions.parse(
|
|
model=model_name,
|
|
messages=messages,
|
|
temperature=temperature,
|
|
top_p=top_p,
|
|
reasoning_effort=reasoning_effort,
|
|
# max_tokens=max_token,
|
|
stop=None,
|
|
response_format=output_schema,
|
|
)
|
|
print(f'response {response}')
|
|
if response and response.choices and response.choices[0].message.parsed:
|
|
parsed = response.choices[0].message.parsed
|
|
try:
|
|
parsed = output_schema.model_validate(parsed)
|
|
parsed = dict(parsed.model_dump())
|
|
except Exception:
|
|
parsed = str(parsed)
|
|
|
|
final_output.append(
|
|
{
|
|
"id": item["id"],
|
|
"text": item["text"],
|
|
"ai_recode": {
|
|
"ai_code_version": "gemma3_27b_med_rescore",
|
|
"ai_result": parsed['result'],
|
|
},
|
|
}
|
|
)
|
|
processed_id.append(item["id"])
|
|
|
|
except Exception as e:
|
|
print(f"⚠️ Error on {item.get('id', 'unknown')}: {e}")
|
|
|
|
# 🔹 Loop over the batch (list of items) and await each item
|
|
await asyncio.gather(*(process_item(it) for it in data_batch))
|
|
|
|
# ذخیره کل batch در یک فایل
|
|
save_orjson(
|
|
data=final_output, path=os.path.join(base_dir, f"{batch_file_name}.json")
|
|
)
|
|
|
|
print(f"✅ Worker done: {len(data_batch)} item ")
|
|
|
|
# اجرای async
|
|
asyncio.run(worker_loop())
|
|
|
|
|
|
def llm_eval(
|
|
llm_url,
|
|
base_dir,
|
|
data, # اینجا لیست تو در تو از batchها
|
|
max_token,
|
|
output_schema,
|
|
temperature,
|
|
top_p,
|
|
reasoning_effort,
|
|
n_workers,
|
|
model_name,
|
|
):
|
|
"""اجرای پردازش موازی، هر Worker یک batch کامل"""
|
|
if not os.path.exists(base_dir):
|
|
os.makedirs(base_dir)
|
|
|
|
file_number = get_max_number_file(base_dir)
|
|
print(f"🚀 Launching {n_workers} parallel workers (each async)...")
|
|
|
|
# تقسیم batches بین Workerها
|
|
args = []
|
|
for i, batch in enumerate(data):
|
|
args.append(
|
|
(
|
|
llm_url,
|
|
base_dir,
|
|
batch, # لیست تو در تو همان batch
|
|
model_name,
|
|
output_schema,
|
|
temperature,
|
|
top_p,
|
|
reasoning_effort,
|
|
max_token,
|
|
f"output_worker_{i+1+file_number}",
|
|
)
|
|
)
|
|
|
|
# اجرای parallel
|
|
with multiprocessing.Pool(processes=n_workers) as pool:
|
|
pool.starmap(single_worker_process, args)
|
|
|
|
print("✅ All workers finished successfully.")
|
|
|
|
|
|
def chunk_list(data, size):
|
|
"""تبدیل لیست فلت به لیستهای تو در تو با اندازه مشخص"""
|
|
chunks = []
|
|
for i in range(0, len(data), size):
|
|
chunk = []
|
|
for j in range(i, min(i + size, len(data))):
|
|
chunk.append(data[j])
|
|
chunks.append(chunk)
|
|
return chunks
|
|
|
|
|
|
def prepare_data(
|
|
all_data,
|
|
processed_ids,
|
|
system_prompt,
|
|
assisst_data,
|
|
assistant_prompt=None,
|
|
batch_size=20,
|
|
):
|
|
processed_ids = set(processed_ids)
|
|
filtered_data = [item for item in all_data if item["id"] not in processed_ids]
|
|
print(f"📦 All Data {len(all_data)} Filtered: {len(filtered_data)}")
|
|
|
|
results = [
|
|
{
|
|
"id": item["id"],
|
|
"text": item["text"],
|
|
"user_prompt": f"text: `{item['text']}`\nresult: `{item['ai_code']['ai_code_ner_result']['result']}`",
|
|
"system_prompt": system_prompt,
|
|
**({"assistant_prompt": assistant_prompt} if assistant_prompt else {}),
|
|
}
|
|
for item in filtered_data
|
|
]
|
|
results = chunk_list(results, batch_size)
|
|
print(f"✅ Final: {len(results)}")
|
|
return results
|
|
|
|
|
|
def main(
|
|
system_prompt,
|
|
assistant_prompt,
|
|
all_data,
|
|
processed_ids,
|
|
assisst_data,
|
|
batch_size,
|
|
model_name,
|
|
llm_url,
|
|
base_dir,
|
|
max_token,
|
|
output_schema,
|
|
temperature,
|
|
top_p,
|
|
reasoning_effort,
|
|
n_workers,
|
|
):
|
|
start_data = time.time()
|
|
try:
|
|
f_data = prepare_data(
|
|
system_prompt=system_prompt,
|
|
assistant_prompt=assistant_prompt,
|
|
all_data=all_data,
|
|
processed_ids=processed_ids,
|
|
assisst_data=assisst_data,
|
|
batch_size=batch_size,
|
|
)
|
|
except KeyboardInterrupt:
|
|
import traceback
|
|
|
|
print(f"ERROR:{traceback.print_exc()}")
|
|
print("⛔ Interrupted by user In prepare_data")
|
|
|
|
end_data = time.time()
|
|
print(f"Total Time in Data-Proccess {end_data-start_data:.2f}")
|
|
|
|
######### پردازش چندین هسته ای
|
|
try:
|
|
llm_eval(
|
|
model_name=model_name,
|
|
llm_url=llm_url,
|
|
base_dir=base_dir,
|
|
data=f_data, # list of user prompt generated
|
|
max_token=max_token,
|
|
output_schema=output_schema,
|
|
temperature=temperature,
|
|
top_p=top_p,
|
|
reasoning_effort=reasoning_effort,
|
|
n_workers=n_workers,
|
|
)
|
|
except KeyboardInterrupt:
|
|
print("⛔ Interrupted by user")
|
|
|
|
end_llm = time.time()
|
|
print(f"Total Time in Data-Proccess {end_llm-end_data:.2f}")
|
|
|
|
|
|
|
|
def merge_json_dir(input_path, output_path):
|
|
directory = Path(input_path)
|
|
if not directory.is_dir():
|
|
raise ValueError(f"Not valid PATH: {input_path}")
|
|
|
|
all_data = []
|
|
failed_files = []
|
|
|
|
# پیدا کردن تمام فایلهای .json در دایرکتوری
|
|
json_files = list(directory.glob("*.json"))
|
|
|
|
if not json_files:
|
|
print("⚠️ NO jsoN FIle Found In THis paTH")
|
|
return
|
|
|
|
for json_file in json_files:
|
|
try:
|
|
data = load_orjson(json_file)
|
|
if len(data) == 0:
|
|
failed_files.append(json_file.name)
|
|
continue
|
|
if isinstance(data, list) and isinstance(data[0], dict):
|
|
all_data.extend(data)
|
|
# print(f"✅ {json_file.name} با موفقیت اضافه شد.")
|
|
else:
|
|
raise ValueError(f"no list available in this json ->{json_file}")
|
|
except (json.JSONDecodeError, ValueError, OSError) as e:
|
|
print(f"❌ Faild in proccess '{json_file.name}': {e}")
|
|
failed_files.append(json_file.name)
|
|
|
|
# گزارش فایلهایی که اضافه نشدند
|
|
if failed_files:
|
|
print("\n❌ We lose this file")
|
|
for name in failed_files:
|
|
print(f" - {name}")
|
|
else:
|
|
print("\n✅ All json added")
|
|
|
|
# ذخیره خروجی در همان دایرکتوری
|
|
try:
|
|
save_orjson(data=all_data, path=output_path)
|
|
print(f"\n💾 finall file saved {output_path}")
|
|
except Exception as e:
|
|
print(f"❌error in sAve finall file {e}")
|
|
|
|
|
|
def make_new_proccessed_ids_from_file(json_in, out_path):
|
|
data = load_orjson(json_in)
|
|
|
|
finall_data = []
|
|
for d in data:
|
|
if d['id']:
|
|
finall_data.append(d["id"])
|
|
finall_data = set(finall_data)
|
|
finall_data = list(finall_data)
|
|
|
|
save_orjson(
|
|
data=finall_data,
|
|
path=out_path
|
|
)
|
|
|
|
|
|
|
|
# --------------------------------- Base-Model
|
|
SYSTEM_PROMPT = """You are a precise NER evaluation model.
|
|
Your task is to verify whether the extracted entities in "result" are fully correct, relevant, and consistent with the "text".
|
|
If all labeled entities are accurate and appropriate, respond only with: `True`
|
|
If any label, entity, or position is wrong, incomplete, or irrelevant, respond only with: `False`
|
|
Do not explain. Output must be strictly `True` or `False`.
|
|
|
|
### Example Format:
|
|
{
|
|
"text": "...",
|
|
"result": [
|
|
{"label": "...", "word": "...", "index": ...},
|
|
...
|
|
]
|
|
}
|
|
|
|
"""
|
|
|
|
|
|
class OutputModel(BaseModel):
|
|
result : bool
|
|
|
|
|
|
if __name__ == "__main__":
|
|
n_workers_Av = multiprocessing.cpu_count()
|
|
print(f"System has {n_workers_Av} CPUs")
|
|
# base_dir= "./ner_data_jokar_oss120b_med_p2/batch_data"
|
|
base_dir= "/home1/ava3/ner_jokar/ner_data_jokar_gemma27b_med_p3/batch_data"
|
|
############# # آماده سازی نهایی داده
|
|
all_data = load_orjson("/home1/ava3/ner_jokar/ner_data_jokar_oss120b_med_p2/finall_data.json")
|
|
all_data = all_data[:2]
|
|
# json_all = f"{base_dir}/high/merged_all.json"
|
|
|
|
# merge_json_dir(input_path=base_dir, output_path=json_all)
|
|
# make_new_proccessed_ids_from_file(json_in=json_all, out_path="./processed_ids.json")
|
|
|
|
# processed_ids = load_orjson("/home1/ava3/ner_jokar/ner_data_jokar_oss120b_med_p2/proccessed_id.json")
|
|
# processed_ids = ["qs2401193","qs995071","qs503450","qs748067","qs856485","qs934533","qs2403889","qs866504",]
|
|
# processed_ids.extend(processed_ids1)
|
|
processed_ids = []
|
|
main(
|
|
system_prompt=SYSTEM_PROMPT,
|
|
assistant_prompt=None,
|
|
all_data=all_data,
|
|
assisst_data=None,
|
|
processed_ids=processed_ids,
|
|
batch_size=1,
|
|
model_name="gemma-3-27b-it",
|
|
llm_url="http://localhost:8001/v1/",
|
|
base_dir=base_dir,
|
|
max_token=8192,
|
|
output_schema=OutputModel,
|
|
temperature=0.0,
|
|
top_p=0.1,
|
|
reasoning_effort="low", # medium
|
|
n_workers=2,
|
|
)
|
|
print(":D")
|