Files
AiDataParser/task/match_plan/v1/phase2_main_code.py
T
2026-11-28 16:36:19 +00:00

190 lines
6.5 KiB
Python
Executable File

# ------------------------------- moddularity
import os
# import pandas as pd
import orjson
import json
import re
import unicodedata
import tiktoken
import orjson
from typing import List, Optional
from pydantic import BaseModel, validator
from pathlib import Path
import time
from static_data import ( title_77_fr_normalized_translated,
title_77_fr,
title_dict_translate,
title_77_fr_ids,
title_49_per,
rel_one2many,
rel_incomplate
)
from openai import OpenAI
# ------------------------------- func
def load_json(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 count_tokens(model_name, system_prompt, user_prompt):
"""
شمارش دقیق توکن‌های ورودی برای مدل‌های مختلف
"""
text = f"<|system|>\n{system_prompt}\n<|user|>\n{user_prompt}"
# --- انتخاب tokenizer ---
if "openai" in model_name.lower() or "oss" in model_name.lower():
# مدل‌های مشابه GPT یا OSS از tiktoken استفاده می‌کنند
enc = tiktoken.get_encoding("cl100k_base")
tokens = enc.encode(text)
return len(tokens)
elif "gemma" in model_name.lower():
from transformers import AutoTokenizer
# SentencePiece tokenizer (Gemma از HuggingFace)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokens = tokenizer.encode(text)
return len(tokens)
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)
return len(tokens)
else:
raise ValueError(f"Model {model_name} not recognized.")
def chat_llm(model_name,output_model,max_tokens, client,system_prompt, user_prompt ):
"""پردازش هر آیتم جداگانه به صورت async"""
# print(f"✅ Batch of {len(api_batch)} done in {elapsed:.2f}s | Mean: {mean_time:.2f}s")
try:
start = time.time()
response = client.chat.completions.parse(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
# {"role": "assistant", "content": item["assistant_prompt"]},
],
temperature=0,
top_p=1,
reasoning_effort="high",
max_tokens=max_tokens,
stop=None,
response_format=output_model,
)
print(F'response {response}')
if response and response.choices and response.choices[0].message.parsed:
result = response.choices[0].message.parsed
# ✅ 1. Validate and serialize with the Pydantic model
validated = output_model.model_validate(result)
# ✅ 2. Convert model to dict for JSON serialization
validated_dict = validated.model_dump()
# ✅ 3. Convert to JSON string
result_json = json.dumps(validated_dict, ensure_ascii=False)
end = time.time()
print(f"✅ Time: {end - start:.2f}s")
return result_json
else:
print("⚠️ No parsed output returned.")
return response
except Exception as e:
import traceback
print(f"⚠️ Error on {user_prompt}: {e}")
print(f"⚠️ Error on {traceback.print_exc()}")
f_data = load_json('./finall_prompt.json')
def_data = load_json('./prompt_ir_def.json')
class Section(BaseModel):
title: str
subsections: Optional[List['Section']] = None # نوع به صورت رشته‌ای
class LawStructure(BaseModel):
law_title: str
sections: List[Section]
Section.model_rebuild()
max_token = 100000
model_name = "gpt-oss-120b"
LLM_URL = "http://localhost:8001/v1/"
client = OpenAI(base_url=LLM_URL, api_key="EMPTY")
for k, v in rel_one2many.items():
if isinstance(v, list) and len(v) == 1:
new_title = k
sub_title = v[0]
new_title_definition = def_data[new_title]["description"]
sub_title_arch = f_data[new_title][sub_title]
_system_prompt = f"""
شما یک حقوقدان و متخصص طبقه‌بندی قوانین هستید.
وظیفه شما:
- برای عنوان های قوانین جدید، ساختار تو در تو بسازید
- ساختار باید شامل: عنوان، فصل، بخش و بند باشد (به همان فرم سلسله مراتبی موجود)
- عناوین و زیرمجموعه ها باید دقیق و مرتبط با موضوع باشند
- هیچ متن توضیحی اضافی ننویسید
- بسیار کامل و جامع خروجی بده
- فقط JSON خروجی بدهید که مطابق مدل زیر باشد:
- عناوین گویا و فارسی باید باشند
{{
"law_title": "عنوان قانون",
"sections": [
{{
"title": "عنوان/فصل/بخش",
"subsections": [
... همین ساختار
]
}}
]
}}
نمونه مرجع ساختار قانون مشابه ({sub_title}):
{sub_title_arch}
"""
_user_prompt = f"""
عنوان قانون: {new_title}
تعریف قانون: {new_title_definition}
"""
number = count_tokens(model_name=model_name, system_prompt=_system_prompt, user_prompt=_user_prompt)
print(f"new_title {new_title} number {number}")
resones = chat_llm(
model_name=model_name,
output_model=LawStructure,
max_tokens=100000,
client=client,
system_prompt=_system_prompt,
user_prompt=_user_prompt
)
try:
print('Json saved!')
with open(f'./finall_arch_data/{new_title}.json', "wb") as f:
f.write(orjson.dumps(resones, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS))
except:
print('TXT saved!')
with open(f'./finall_arch_data/{new_title}.text', "w") as f:
f.write(resones)