539 lines
21 KiB
Python
Executable File
539 lines
21 KiB
Python
Executable File
from typing import List, Optional
|
||
import json
|
||
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 json
|
||
import os
|
||
import time
|
||
from dotenv import load_dotenv
|
||
from pydantic import BaseModel
|
||
from openai import OpenAI
|
||
import re
|
||
from typing import List
|
||
import asyncio
|
||
import time
|
||
import asyncio
|
||
import multiprocessing
|
||
import os
|
||
import time
|
||
from openai import OpenAI
|
||
from functools import partial
|
||
|
||
|
||
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())
|
||
|
||
# --------------------------------- Base-Model
|
||
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
|
||
|
||
|
||
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
|
||
}}
|
||
"""
|
||
|
||
|
||
|
||
# ------------------------------ 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
|
||
max_file = None
|
||
|
||
for filename in os.listdir(directory):
|
||
match = pattern.match(filename)
|
||
if match:
|
||
num = int(match.group(1))
|
||
if num > max_num:
|
||
max_num = num
|
||
max_file = filename
|
||
return max_num + 1
|
||
|
||
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 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)]
|
||
|
||
# تابع برش و آماده کردن لیست ها (batchs)
|
||
async def prepare_batches(all_data, ignor_ids, proccessed_id, system_prompt=SYSTEM_PROPMT, assistant_prompt=ASSISTANT_PROMPT, user_prompt='', batch_file_size=1000):
|
||
api_batch = []
|
||
for item in all_data:
|
||
_id = item["id"]
|
||
|
||
|
||
# فیلتر کردن IDهای غیرمجاز
|
||
if _id in proccessed_id:
|
||
continue
|
||
|
||
word = item["word"]
|
||
user_prompt = f"Input: `{word}`"
|
||
|
||
api_batch.append({
|
||
"_id": _id,
|
||
"user_prompt": str(user_prompt),
|
||
"system_prompt": str(system_prompt),
|
||
"assistant_prompt": str(assistant_prompt),
|
||
"word": word,
|
||
})
|
||
|
||
# وقتی batch پر شد
|
||
if len(api_batch) >= batch_file_size:
|
||
yield api_batch
|
||
api_batch = []
|
||
|
||
# آخرین batch ناقص
|
||
if api_batch:
|
||
yield api_batch
|
||
|
||
# پردازش ناهمگام batchها
|
||
async def process_api_batch(client, model, api_batch, processed_id, total_times):
|
||
start_time = time.time()
|
||
final_output = []
|
||
|
||
async def process_item(item):
|
||
"""پردازش هر آیتم جداگانه به صورت async"""
|
||
# print(f"✅ Batch of {len(api_batch)} done in {elapsed:.2f}s | Mean: {mean_time:.2f}s")
|
||
try:
|
||
response = client.chat.completions.parse(
|
||
model=model,
|
||
messages=[
|
||
{"role": "system", "content": item["system_prompt"]},
|
||
{"role": "user", "content": item["user_prompt"]},
|
||
{"role": "assistant", "content": item["assistant_prompt"]},
|
||
],
|
||
temperature=0,
|
||
top_p=1,
|
||
reasoning_effort="medium",
|
||
max_tokens=8192,
|
||
stop=None,
|
||
response_format=WordCorrector,
|
||
)
|
||
|
||
if response and response.choices and response.choices[0].message.parsed:
|
||
parsed = response.choices[0].message.parsed
|
||
|
||
try:
|
||
parsed = WordCorrector.model_validate(parsed)
|
||
parsed = parsed.model_dump()
|
||
parsed = dict(parsed)
|
||
except Exception as e:
|
||
parsed = str(parsed)
|
||
|
||
final_output.append({
|
||
"id": item["_id"],
|
||
"word": item["word"],
|
||
"ai_code": {
|
||
'ai_code_version':"gemma27b_v1_med",
|
||
'ai_code':parsed,
|
||
}
|
||
})
|
||
processed_id.append(item["_id"])
|
||
|
||
except Exception as e:
|
||
print(f"⚠️ Error on {item['_id']}: {e}")
|
||
# اجرای همزمان تمام آیتمها در این batch
|
||
await asyncio.gather(*(process_item(it) for it in api_batch))
|
||
|
||
# محاسبه زمان میانگین
|
||
elapsed = time.time() - start_time
|
||
total_times.append(elapsed)
|
||
mean_time = sum(total_times) / len(total_times)
|
||
print(f"✅ Batch of {len(api_batch)} done in {elapsed:.2f}s | Mean: {mean_time:.2f}s")
|
||
|
||
return final_output
|
||
|
||
# تابع اتصال و انجام دهنده پردازش هر batch
|
||
async def consume_batches(client, model, batch_generator, processed_id, total_times, base_dir):
|
||
print(f'consume_batches start')
|
||
batch_file_number = get_max_number_file(base_dir)
|
||
total_answer = 0
|
||
async for api_batch in batch_generator:
|
||
final_output = await process_api_batch(client, model, api_batch, processed_id, total_times)
|
||
print(f'batch done --total_answer {total_answer}')
|
||
total_answer += 200
|
||
|
||
if total_answer >= 9 :
|
||
# ذخیره خروجی
|
||
out_path = f"output_{batch_file_number}.json"
|
||
save_orjson(os.path.join(base_dir,out_path), final_output)
|
||
|
||
print(f"💾 Saved {len(final_output)} records to {out_path}")
|
||
batch_file_number += 1
|
||
total_answer = 0
|
||
|
||
# ذخیره شناسههای پردازششده
|
||
save_orjson(os.path.join(base_dir,"processed_id.json"), processed_id)
|
||
|
||
# تابع main
|
||
async def async_code_eval(llm_url ='http://localhost:8100/v1/', base_dir='./data_gemma3_27b', batch_size=200):
|
||
t1 = time.time()
|
||
client = OpenAI(base_url=llm_url, api_key="EMPTY")
|
||
|
||
print("🔹 Loading data files...")
|
||
|
||
words = load_json('word_list.json')
|
||
ignored_ids = [] #load_json('word_list.json')
|
||
|
||
total_times = []
|
||
processed_id = []
|
||
t2 = time.time()
|
||
print(f'words {len(words)}')
|
||
print(f'Step1 ✅: loaded -> time -> {t2-t1:.2f}s')
|
||
batch_gen = prepare_batches(
|
||
all_data=words,
|
||
ignor_ids=ignored_ids,
|
||
proccessed_id=[],
|
||
batch_file_size=batch_size
|
||
)
|
||
# print(f'batch_gen {len(batch_gen)}')
|
||
t3 = time.time()
|
||
delta = t3-t2
|
||
print(f'Step2 ✅: data normalized -> time -> {delta:.2f}s')
|
||
|
||
await consume_batches(client=client, model=MODEL, batch_generator=batch_gen, processed_id=processed_id, total_times=total_times, base_dir=base_dir)
|
||
t4 = time.time()
|
||
delta = t4-t3
|
||
|
||
print(f'Step3 ✅: model generated -> time -> {delta:.2f}s')
|
||
delta = t4-t1
|
||
print(f"✅ Done. Total processed: {len(processed_id)} finall Time {delta:.2f}s")
|
||
|
||
# -------------------------------------------------------------------- Run
|
||
if __name__ == "__main__":
|
||
import time
|
||
import orjson
|
||
# MODEL = '/home2/gpt-oss-20b'
|
||
MODEL = 'gemma-3-27b-it'
|
||
try:
|
||
asyncio.run(async_code_eval(base_dir='./data_gemma3_27b', batch_size=100))
|
||
except KeyboardInterrupt:
|
||
print("⛔ Interrupted by user")
|
||
|