to-164
This commit is contained in:
Executable
+404
@@ -0,0 +1,404 @@
|
||||
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
|
||||
|
||||
# -------------------------- func
|
||||
|
||||
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)]
|
||||
|
||||
import json
|
||||
|
||||
def single_worker_process(
|
||||
llm_url, base_dir, data_batch, model_name,
|
||||
output_schema, temperature, top_p, reasoning_effort,
|
||||
max_token, batch_file_name
|
||||
):
|
||||
"""هر فرایند جداگانه یک event loop مخصوص خودش اجرا میکند."""
|
||||
client = OpenAI(base_url=llm_url, api_key="EMPTY")
|
||||
|
||||
async def worker_loop():
|
||||
final_output = []
|
||||
processed_id = []
|
||||
|
||||
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 = client.chat.completions.parse(
|
||||
response = client.chat.completions.parse( #create
|
||||
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,
|
||||
)
|
||||
|
||||
parsed = None
|
||||
# --- حالت ۱: پاسخ parse شده توسط vLLM ---
|
||||
if response and response.choices and getattr(response.choices[0].message, "parsed", None):
|
||||
parsed = response.choices[0].message.parsed
|
||||
# --- حالت ۲: اگر parse در دسترس نبود ---
|
||||
elif response and response.choices and hasattr(response.choices[0].message, "content"):
|
||||
parsed = response.choices[0].message.content
|
||||
else:
|
||||
parsed = str(response)
|
||||
|
||||
# --- تلاش برای validate و تبدیل ---
|
||||
try:
|
||||
# print("✅")
|
||||
parsed = output_schema.model_validate(parsed)
|
||||
parsed = dict(parsed.model_dump())
|
||||
except Exception as inner_e:
|
||||
print(f"❌ schema validation failed: {inner_e}")
|
||||
# اگر JSON بود ولی ناقص:
|
||||
try:
|
||||
parsed = json.loads(str(parsed))
|
||||
if isinstance(parsed, dict):
|
||||
parsed = dict(parsed)
|
||||
else:
|
||||
parsed = {"raw_text": str(parsed)}
|
||||
except Exception:
|
||||
# آخرین fallback: رشته خام
|
||||
parsed = {"raw_text": str(parsed)}
|
||||
parsed = {
|
||||
'ai_result':parsed,
|
||||
"version_key": "D49_v2"
|
||||
}
|
||||
f_item = item["item"]
|
||||
f_item['diff_ai'] = parsed
|
||||
|
||||
final_output.append(f_item)
|
||||
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')
|
||||
)
|
||||
# data_procc_ids = load_orjson(
|
||||
# path=os.path.join(base_dir, 'proccessed_id.json')
|
||||
# )
|
||||
# data_procc_ids.extend(processed_id)
|
||||
# processed_id = []
|
||||
# save_orjson(
|
||||
# data=data_procc_ids,
|
||||
# path=os.path.join(base_dir, 'proccessed_id.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"📦 Data: {len(all_data)} - {len(processed_ids)} = {len(filtered_data)}")
|
||||
|
||||
domain_data_raw = load_orjson('/home1/ava3/diff_llm_tanghih/legal_prompt.json')
|
||||
domain_data_all = {}
|
||||
|
||||
for k, v in domain_data_raw.items():
|
||||
domain_data_all[k] = v['description']
|
||||
|
||||
# domain_prompt = prompts[label]["open_ai"]
|
||||
results = []
|
||||
for item in filtered_data:
|
||||
domain_in = set()
|
||||
history_code = {}
|
||||
domain_data = {}
|
||||
|
||||
# -------- domain_in START
|
||||
domain_in.add(item['ai_code']['label'])
|
||||
|
||||
if len(item['tcode_mains']) == 1:
|
||||
domain_in.add(item['tcode_mains'][0])
|
||||
|
||||
if len(item['tcode_subs']) == 1:
|
||||
domain_in.add(item['tcode_subs'][0])
|
||||
|
||||
for j in item['ai_codes']:
|
||||
domain_in.add(j['label'])
|
||||
|
||||
is_history_codes = item.get('history_codes')
|
||||
|
||||
if is_history_codes:
|
||||
domain_in.add(item['history_codes'][0]['label'])
|
||||
# -------- domain_in END
|
||||
|
||||
# -------- history_codes START
|
||||
if is_history_codes:
|
||||
history_code['label'] = item['history_codes'][0]['label']
|
||||
history_code['description'] = item['history_codes'][0]['description']
|
||||
# -------- history_codes END
|
||||
|
||||
# -------- history_codes START
|
||||
for i in domain_in:
|
||||
if i in domain_data_raw.keys():
|
||||
domain_data[i] = domain_data_all[i]
|
||||
|
||||
# -------- history_codes END
|
||||
system_prompt = get_system_prompt(domain_data)
|
||||
user_prompt = get_user_prompt(history_code, item["content"], domain_in)
|
||||
|
||||
|
||||
# print(f'item["id"] {item["id"]}')
|
||||
# print(f'user_prompt {user_prompt}')
|
||||
# print(f'system_prompt {system_prompt}')
|
||||
# break
|
||||
results.append({
|
||||
"id": item["id"],
|
||||
"user_prompt": user_prompt,
|
||||
"item": item,
|
||||
"system_prompt": system_prompt,
|
||||
**({"assistant_prompt": assistant_prompt} if assistant_prompt else {})
|
||||
})
|
||||
|
||||
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}")
|
||||
|
||||
|
||||
# --------------------------------- Base-Model
|
||||
|
||||
def get_system_prompt(domain_data):
|
||||
sys = f"""
|
||||
You are a **senior legal expert** specialized in analyzing and correcting domain classification errors made by junior legal analysts.
|
||||
|
||||
You will be given:
|
||||
- The text of a legal article (in Persian).
|
||||
- A list of possible legal domains.
|
||||
- Definitions of each domain.
|
||||
|
||||
Your task:
|
||||
1. Carefully read the legal article.
|
||||
2. Identify which of the given domains **most accurately matches the subject and legal context** of the article.
|
||||
3. Explain briefly **why** this is the correct domain.
|
||||
|
||||
Guidelines:
|
||||
- Base your reasoning on the meaning and function of the legal text, not just keywords.
|
||||
- Choose **only one** correct domain from the provided list.
|
||||
- The explanation should be **short (1–3 lines)**, clear, and in **Persian**.
|
||||
- If multiple domains seem related, select the **most specific** and **directly relevant** one.
|
||||
|
||||
Available domain definitions:
|
||||
{json.dumps(domain_data, ensure_ascii=False, indent=2)}
|
||||
|
||||
Expected output (in JSON format):
|
||||
{{
|
||||
"correct_domain": "<exact domain name from the provided list>",
|
||||
"correct_description": "<short and precise reasoning in Persian>"
|
||||
}}
|
||||
"""
|
||||
# - The expert's classification is most likely wrong.
|
||||
return sys
|
||||
|
||||
|
||||
def get_user_prompt(history_code, content, nearby_domain):
|
||||
if history_code != {}:
|
||||
user = f'''text: {content}\nNearby Domains: {nearby_domain}\nExpert’s initial classification:\n\tDomain: {history_code["label"]}\n\tDescription: {history_code["description"]}'''
|
||||
else:
|
||||
user = f'''text: {content}\nNearby Domains: {nearby_domain}\nThe nExpert’s was unable to identify a domain.'''
|
||||
|
||||
return user
|
||||
|
||||
class ResultLLM(BaseModel):
|
||||
correct_domain:str
|
||||
correct_description:str
|
||||
|
||||
|
||||
ASSISTANT_PROMPT = """
|
||||
Example:
|
||||
|
||||
Input:
|
||||
text: "ماده 118 - اداره ولایتی باموریکه راجع برسیدگی در محاکم عدلیه است دخالت نخواهد کرد یعنی محاکمه نمینماید."
|
||||
Nearby Domains: ["تشکیلات و امور اداری قوه قضائیه", "تقسیمات کشوری و مدیریت محلی", "آیین دادرسی مدنی", "آب", "تعزیرات حکومتی"]
|
||||
Expert’s initial classification:
|
||||
Domain: "تقسیمات کشوری و مدیریت محلی"
|
||||
Description: "اشاره به اداره ولایتی دارد، پس به مدیریت محلی مربوط میشود."
|
||||
|
||||
Corrected Output:
|
||||
{
|
||||
"correct_domain": "تشکیلات و امور اداری قوه قضائیه",
|
||||
"correct_description": "متن درباره حدود صلاحیت قضایی ادارههای محلی در امور دادگستری است و به ساختار قوه قضائیه مربوط میشود."
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n_workers_Av = multiprocessing.cpu_count()
|
||||
print(f"System has {n_workers_Av} CPUs")
|
||||
|
||||
|
||||
############# # آماده سازی نهایی داده
|
||||
all_data = load_orjson('./data_input_2.json')
|
||||
# all_data = all_data[:1]
|
||||
processed_ids = []
|
||||
# processed_ids = load_orjson("/home1/ava3/diff_llm_tanghih/proccessed_id.json")
|
||||
main(
|
||||
assistant_prompt=ASSISTANT_PROMPT,
|
||||
system_prompt=None,
|
||||
all_data=all_data,
|
||||
assisst_data=None,
|
||||
processed_ids=processed_ids,
|
||||
batch_size=1,
|
||||
model_name='gpt-oss-120b',
|
||||
llm_url="http://localhost:8010/v1/",
|
||||
base_dir='./oss_120b_v1',
|
||||
max_token=50000,
|
||||
output_schema=ResultLLM,
|
||||
temperature=0.2,
|
||||
top_p=1,
|
||||
reasoning_effort="medium", # low
|
||||
n_workers=70
|
||||
)
|
||||
print(':D')
|
||||
|
||||
Reference in New Issue
Block a user