to-164
This commit is contained in:
Executable
+623
@@ -0,0 +1,623 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
from pathlib import Path
|
||||
import os
|
||||
import orjson
|
||||
import time
|
||||
import asyncio
|
||||
from openai import AsyncOpenAI
|
||||
import re
|
||||
from functools import partial
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
import multiprocessing
|
||||
import json
|
||||
|
||||
# -------------------------- 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)]
|
||||
|
||||
|
||||
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 = AsyncOpenAI(base_url=llm_url, api_key="EMPTY")
|
||||
|
||||
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 = client.chat.completions.parse(
|
||||
response = await 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:
|
||||
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)}
|
||||
|
||||
|
||||
final_output.append({
|
||||
"id": item["id"],
|
||||
"word": item["word"],
|
||||
"ai_code": {
|
||||
'ai_code_version': "oss120b_v1_med",
|
||||
'ai_code': parsed,
|
||||
}
|
||||
})
|
||||
processed_id.append(item["id"])
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ Error on {item.get('id', 'unknown')}: {e}")
|
||||
|
||||
# 🔹 اجرای همه آیتمها بهصورت concurrent
|
||||
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)}")
|
||||
|
||||
results = [
|
||||
{
|
||||
"id": item["id"],
|
||||
"user_prompt": f"Input: `{item['word']}`",
|
||||
"word": item["word"],
|
||||
"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}")
|
||||
|
||||
|
||||
# --------------------------------- Base-Model
|
||||
|
||||
word_class_dict = {
|
||||
"noun": "اسم",
|
||||
"proper_noun": "اسم خاص", # اسم خاص
|
||||
"plural_noun": "اسم جمع", # اسم جمع
|
||||
"verb": "فعل", # فعل
|
||||
"auxiliary_verb": "فعل کمکی", # فعل کمکی مثل "است"، "می شود"
|
||||
"adjective": "صفت", # صفت
|
||||
"adverb": "قید", # قید
|
||||
"pronoun": "ضمیر", # ضمیر
|
||||
"conjunction": "حرف ربط", # حرف ربط
|
||||
"particle": "حروف ربط کوچک", # مانند "که، را، می، نه"
|
||||
"preposition": "حرف اضافه", # حرف اضافه
|
||||
"interjection": "صوت/حرف ندا", # صوت/حرف ندا
|
||||
"numeral": "عدد", # عدد
|
||||
"determiner": "تعیین کننده", # تعیین کننده ها مثل "این، آن"
|
||||
"classifier": "شمارنده", # مانند "نفر، دانه" ()
|
||||
"modal_verb": "فعل وجهی", # فعل وجهی مثل "باید، بتواند"
|
||||
"brand": "نام تجاری", # اسم برند یا نام تجاری
|
||||
"trademark": "علامت تجاری", # علامت تجاری ثبت شده
|
||||
"nonce": "واژه ساخته شده برای یک موقعیت خاص", # واژه ساخته شده برای یک موقعیت خاص: فعلا برای خداحافظی
|
||||
"constructed": "ساخته شده توسط هوش مصنوعی",
|
||||
"neologism": "واژه تازه ابداع شده", # واژه تازه ابداع شده
|
||||
"unknown": "ناشناخته", # ناشناخته
|
||||
"other": "غیره",
|
||||
}
|
||||
word_class_key = list(word_class_dict.values())
|
||||
|
||||
tags_dict = {
|
||||
"loanword": "واژه وام گرفته شده", # واژهٔ وام گرفته
|
||||
"foreign": "واژه خارجی گردان شده", # خارجی (هنوز به طور کامل وارد زبان نشده)
|
||||
"formal": "رسمی", # رسمی
|
||||
"informal": "غیررسمی", # غیررسمی
|
||||
"colloquial": "محاوره ای/گفتاری", # محاوره ای / گفتاری
|
||||
"slang": "عامیانه", # عامیانه / اصطلاح کوچه بازاری
|
||||
"archaism": "کلمه ای قدیمی که گاهی برای اثر هنری استفاده می شود", # کلمه ای قدیمی که گاهی برای اثر هنری استفاده می شود
|
||||
"obsolete": "کاملاً منسوخ شده", # قدیمی و کاملاً منسوخ شده
|
||||
"dated": "قدیمی ولی هنوز کمی استفاده می شود", # قدیمی ولی هنوز کمی استفاده می شود
|
||||
"historical": "تاریخی", # فقط در بافت تاریخی استفاده می شود
|
||||
"poetic": "کاربرد شعری", # شاعرانه
|
||||
"literary": "ادبی", # ادبی
|
||||
"modern": "مدرن", # مدرن / معاصر
|
||||
"idiomatic": "ضرب المثل", # اصطلاحی (مثل "kick the bucket")
|
||||
"hyperbolic": "اغراق آمیز", # اغراق آمیز
|
||||
# منطقه ای و لهجه ای (Regional / Dialectal)
|
||||
"regional": "منطقه ای", # منطقه ای
|
||||
"dialect": "لهجه ای", # لهجه ای
|
||||
"Tehrani": "فارسی تهرانی", #
|
||||
"qomi": "فارسی قمی", #
|
||||
# ۵. شدت و بار معنایی (Connotation / Tone)
|
||||
"humorous": "طنزآمیز", # طنزآمیز
|
||||
"sarcastic": "کنایه ای", # کنایه ای
|
||||
"ironic": "طعنه آمیز", # طعنه آمیز
|
||||
"offensive": "توهین آمیز", # توهین آمیز
|
||||
"pejorative": "تحقیرآمیز", # منفی و تحقیرآمیز
|
||||
"affectionate": "محبت آمیز", # محبت آمیز
|
||||
"neutral": "خنثی از احساسات", # خنثی
|
||||
"elevated": "فاخر", # سطح بالا و فاخر
|
||||
# ۷. اجتماعی و فرهنگی (Sociolinguistic)
|
||||
"polite": "مؤدبانه", # مؤدبانه
|
||||
"rude": "بی ادبانه", # بی ادبانه
|
||||
"gendered": "جنسیتی (مذکر/مونث)", # جنسیتی (مذکر/مونث)
|
||||
"inclusive": "خنثی جنسیتی", #
|
||||
"racist": "نژادپرستانه", #
|
||||
}
|
||||
tags_key = list(tags_dict.values())
|
||||
|
||||
lang_dict = {
|
||||
"persian":"فارسی", # فارسی
|
||||
"old_persian":"فارسی باستان", # فارسی باستان
|
||||
"arabic":"عربی", # عربی
|
||||
"turkish":"ترکی", # ترکی (اختیاری)
|
||||
"azeri":"آذری", # ترکی (اختیاری)
|
||||
"kurdish":"کردی", # کردی (اختیاری)
|
||||
"english":"انگلیسی", # انگلیسی
|
||||
"US": "گردان شده از انگلیسی آمریکا", #
|
||||
"UK": "گردان شده از انگلیسی بریتانیا", # بریتانیایی
|
||||
"Gulf Arabic": "گردان شده از عربی خلیجی", # عربی خلیجی
|
||||
"Egyptian Arabic": "گردان شده از عربی مصری", # عربی مصری
|
||||
"Yemeni Arabic": "گردان شده از عربی یمن", # عربی مصری
|
||||
"etc":"سایر", # سایر زبان ها
|
||||
}
|
||||
lang_key = list(lang_dict.values())
|
||||
|
||||
scope_dict = {
|
||||
"public":"عمومی",
|
||||
"medical":"پزشکی", # پزشکی
|
||||
"legal":"حقوقی", # حقوقی
|
||||
"scientific":"علمی", # علمی
|
||||
"technical":"فنی", # فنی
|
||||
"religious":"مذهبی", # مذهبی
|
||||
"mythological":"اسطوره ای", # اسطوره ای
|
||||
"military":"نظامی", # نظامی
|
||||
"computing":"کامپیوتری / فناوری اطلاعات", # کامپیوتری / فناوری اطلاعات
|
||||
"internet":"اینترنتی یا دیجیتال", # اینترنتی یا دیجیتال
|
||||
"unknown":"ناشناخته", # ناشناخته
|
||||
"other":"سایر حوزه ها", # سایر حوزه ها
|
||||
# اقتصادی و مالی
|
||||
"economic":"اقتصادی",
|
||||
"financial":"مالی",
|
||||
"trade":"تجارت",
|
||||
"taxation":"مالیات",
|
||||
"budgetary":"بودجه",
|
||||
"industrial":"صنعت",
|
||||
"agricultural":"کشاورزی",
|
||||
"transportation":"حمل و نقل",
|
||||
"real estate":"املاک",
|
||||
"insurance":"بیمه",
|
||||
# اجتماعی و فرهنگی
|
||||
"social":"اجتماعی",
|
||||
"cultural":"فرهنگ",
|
||||
"literary":"ادبیات",
|
||||
"artistic":"هنر",
|
||||
"sports":"ورزش",
|
||||
"family":"خانواده",
|
||||
"educational":"آموزش",
|
||||
"media":"رسانه",
|
||||
"environmental":"محیط زیست",
|
||||
# حکومتی و اداری
|
||||
"administrative":"اداری",
|
||||
"security":"امنیت",
|
||||
"military":"نظامی",
|
||||
"police":"انتظامی",
|
||||
"electoral":"انتخابات",
|
||||
"development":"توسعه",
|
||||
"documentation":"اسناد",
|
||||
"civil":"مدنی",
|
||||
"political":"سیاسی",
|
||||
# تاریخی و علوم انسانی
|
||||
"historical":"تاریخی",
|
||||
"legal":"حقوقی",
|
||||
"religious":"دینی",
|
||||
"philosophical":"فلسفی",
|
||||
"scientific":"علمی",
|
||||
"medical":"پزشکی",
|
||||
"technical":"فنی",
|
||||
"technological":"فناوری",
|
||||
}
|
||||
scope_key = list(scope_dict.values())
|
||||
|
||||
|
||||
class WordCorrector(BaseModel):
|
||||
word: str # کلمه
|
||||
is_correct: bool = False # آیا املای کلمه درست است؟
|
||||
nearest_correct_word: str # کلمه اصلاح شده
|
||||
origin: str = "" # مصدر
|
||||
stem: str = "" # ریشه
|
||||
is_proper_noun: Optional[bool] = False # اگر اسم است: True = خاص، False = عام
|
||||
word_class: Optional[List[str]] = [
|
||||
]
|
||||
|
||||
tags: Optional[List[str]] = [
|
||||
]
|
||||
ner_description: Optional[str] = "" # تشریح کلمه
|
||||
# llm_description: Optional[str] = "" # توضیحات مدل درباره کلمه
|
||||
# user_description: Optional[str] = "" # توضیحات شخص درباره کلمه
|
||||
# admin_description: Optional[str] = "" # توضیحات متخصص درباره کلمه
|
||||
confidence: Optional[float] = None # اطمینان مدل
|
||||
lang: List[str] = [
|
||||
] # زبان کلمه
|
||||
scope: List[str] = [
|
||||
] # حوزه کاربرد کلمه
|
||||
|
||||
|
||||
|
||||
class ProWord(BaseModel):
|
||||
word: str # کلمه ورودی یا اصلاح شده
|
||||
is_correct: bool # آیا املای کلمه درست است؟
|
||||
origin: Optional[str] = "" # مصدر یا ریشه کلمه (مثلاً برای "رفت" → "رفتن")
|
||||
word_class: Optional[
|
||||
str
|
||||
] # نوع دستوری: noun, verb, adjective, adverb, pronoun, conjunction, preposition, interjection, numeral
|
||||
proper_noun: Optional[bool] # اگر اسم است: True = خاص، False = عام
|
||||
tags: Optional[List[str]] = (
|
||||
[]
|
||||
) # تگ های آزاد مثل ["plural", "informal", "colloquial"]
|
||||
description: Optional[str] = "" # توضیح مدل درباره کلمه و کاربردش
|
||||
confidence: Optional[float] = None
|
||||
|
||||
# class WordCorrector(BaseModel):
|
||||
# corrected: str
|
||||
# reason: str
|
||||
|
||||
|
||||
|
||||
model = ""
|
||||
name="persian-word-analyzer",
|
||||
description="Analyzes a Persian word for spelling, grammar, and linguistic properties.",
|
||||
system_prompt_WordCorrector = f"""You are a professional linguist and Persian lexical annotator.
|
||||
Your task is to analyze each given word and produce a detailed JSON entry following the WordCorrector schema.
|
||||
- if the word is not correct just fill the is_correct == false and return it
|
||||
|
||||
⚠️ You must choose ONLY from the allowed options listed below for each category.
|
||||
If unsure, use "unknown". Never invent new items.
|
||||
|
||||
### Allowed options:
|
||||
- word_class (choose one or more from):
|
||||
{word_class_key}
|
||||
|
||||
- tags (choose one or more from):
|
||||
{tags_key}
|
||||
|
||||
- lang (choose only):
|
||||
{lang_key}
|
||||
|
||||
- scope (choose one or more from):
|
||||
{scope_key}
|
||||
|
||||
---
|
||||
|
||||
### output must match exactly:
|
||||
{{
|
||||
"word": exact word text
|
||||
"is_correct": true or false
|
||||
"nearest_correct_word": nearest word to this word from char CER form if meaningfull از لحاظ فرم نوشتاری
|
||||
"origin": ریشه کلمه
|
||||
"stem": مصدر کلمه
|
||||
"is_proper_noun": آیا اسم خاص است این کلمه اگر بود true در غیر این صورت false
|
||||
"word_class": معنی گرامری این کلمه چیست ؟؟
|
||||
"tags": چه نوعیت هایی دارد این کلمه ؟؟
|
||||
"ner_description":تشریح کلمه
|
||||
"lang": این کلمه از چه زبانی است ؟؟ حتی اگر گردان از آن زبان باشد بر اساس لیست داده شده
|
||||
"scope": در چه حوزه هایی کاردبرد دارد این کلمه ؟؟؟
|
||||
}}
|
||||
|
||||
Rules:
|
||||
1. Output MUST be valid JSON — no explanation or comments.
|
||||
2. Each key must be included, even if empty.
|
||||
3. Confidence: float between 0 and 1.
|
||||
4. Use lowercase for all values.
|
||||
5. If the spelling is correct → `is_correct: true`, otherwise `false`.
|
||||
6. If not sure about a category → include "unknown" in that list.
|
||||
|
||||
---"""
|
||||
|
||||
SYSTEM_PROPMT = f"""You are an expert **Persian linguist and lexical annotator**.
|
||||
Your goal is to analyze each given Persian word and produce **one valid JSON object** that matches the **WordCorrector schema** exactly.
|
||||
|
||||
Output must always follow these rules:
|
||||
- Output **only valid JSON** (no text, no Markdown, no explanation).
|
||||
- Include **all fields** (even if empty or null).
|
||||
- Use **lowercase Persian** for all string values.
|
||||
- For categorical fields, select values **only from the allowed lists** below.
|
||||
- Do not create new labels or lists.
|
||||
- Ensure `"confidence"` is a float between `0.0` and `1.0`.
|
||||
- If the word’s spelling is wrong, set `"is_correct": false` and provide `"nearest_correct_word"` as the corrected or normalized form.
|
||||
|
||||
---
|
||||
|
||||
### FIELD GUIDE
|
||||
|
||||
| Field | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `word` | string | Exact input word. |
|
||||
| `is_correct` | boolean | `true` if spelling is correct; otherwise `false`. |
|
||||
| `nearest_correct_word` | string | The corrected or normalized word form. |
|
||||
| `origin` | string | Etymological root — the most basic source unit. |
|
||||
| `stem` | string | Morphological or infinitive form (for verbs). |
|
||||
| `is_proper_noun` | boolean | `true` for specific entities (persons, places, brands). |
|
||||
| `word_class` | list[string] | One or more grammatical classes (from allowed list). |
|
||||
| `tags` | list[string] | Stylistic or register-related tags (from allowed list). |
|
||||
| `ner_description` | string | Concise semantic or contextual description. |
|
||||
| `lang` | list[string] | Language of origin (from allowed list). |
|
||||
| `scope` | list[string] | Domain or field of common use (from allowed list). |
|
||||
| `confidence` | float | Model certainty (0.0–1.0). |
|
||||
|
||||
---
|
||||
|
||||
### ALLOWED OPTIONS
|
||||
|
||||
#### **word_class**
|
||||
{word_class_key}
|
||||
|
||||
#### **tags**
|
||||
{tags_key}
|
||||
|
||||
#### **lang**
|
||||
{lang_key}
|
||||
|
||||
#### **scope**
|
||||
{scope_key}
|
||||
|
||||
### RULES
|
||||
|
||||
1. Output must be **valid JSON only**.
|
||||
2. Always include **all fields**, even if empty.
|
||||
3. Use **lowercase** for all string values.
|
||||
4. Never invent new tags, word_classes, langs, or scopes.
|
||||
5. For categorical fields, select **only from allowed options**.
|
||||
6. Confidence must be a float between `0.0` and `1.0`.
|
||||
"""
|
||||
|
||||
ASSISTANT_PROMPT = """#### Example 1
|
||||
Input: `نوشتم`
|
||||
Output:
|
||||
{{
|
||||
"word": "نوشتم",
|
||||
"is_correct": true,
|
||||
"nearest_correct_word": "نوشتم",
|
||||
"origin": "نوشت",
|
||||
"stem": "نوشتن",
|
||||
"is_proper_noun": false,
|
||||
"word_class": ["فعل"],
|
||||
"tags": ["رسمی","خنثی جنسیتی"],
|
||||
"ner_description": "فعل فارسی برای اول شخص مفرد از مصدر نوشتن",
|
||||
"lang": ["فارسی"],
|
||||
"scope": ["عمومی"],
|
||||
"confidence": 1.0
|
||||
}}
|
||||
|
||||
#### Example 2
|
||||
Input: `نبشتم`
|
||||
Output:
|
||||
{{
|
||||
"word": "نبشتم",
|
||||
"is_correct": true,
|
||||
"nearest_correct_word": "نوشتم",
|
||||
"origin": "نوشت",
|
||||
"stem": "نوشتن",
|
||||
"is_proper_noun": false,
|
||||
"word_class": ["فعل"],
|
||||
"tags": ["کلمه ای قدیمی که گاهی برای اثر هنری استفاده می شود","تاریخی","کاربرد شعری","ادبی","لهجه ای","فاخر"],
|
||||
"ner_description": "صورت قدیمیتر فعل نوشتم که در فارسی کهن و اشعار کلاسیک کاربرد داشته است",
|
||||
"lang": ["فارسی باستان"],
|
||||
"scope": ["فرهنگ", "ادبیات", "تاریخی"],
|
||||
"confidence": 0.98
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n_workers_Av = multiprocessing.cpu_count()
|
||||
print(f"System has {n_workers_Av} CPUs")
|
||||
|
||||
|
||||
############# # آماده سازی نهایی داده
|
||||
all_data = load_orjson('./word_list.json')
|
||||
processed_ids = load_orjson("/home1/ava3/word_bank_proccess/oss_120b_v1/proccessed_id.json")
|
||||
main(
|
||||
system_prompt=SYSTEM_PROPMT,
|
||||
assistant_prompt=ASSISTANT_PROMPT,
|
||||
all_data=all_data,
|
||||
assisst_data=None,
|
||||
processed_ids=processed_ids,
|
||||
batch_size=10,
|
||||
model_name='gpt-oss-120b',
|
||||
llm_url="http://localhost:8010/v1/",
|
||||
base_dir='/home1/ava3/word_bank_proccess/oss_120b_v1/batch_data',
|
||||
max_token=48000,
|
||||
output_schema=WordCorrector,
|
||||
temperature=0.2,
|
||||
top_p=0.9,
|
||||
reasoning_effort="medium", # low
|
||||
n_workers=10
|
||||
)
|
||||
print(':D')
|
||||
|
||||
Reference in New Issue
Block a user