to-164
This commit is contained in:
Executable
+538
@@ -0,0 +1,538 @@
|
||||
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")
|
||||
|
||||
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')
|
||||
|
||||
Executable
+302
@@ -0,0 +1,302 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
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 merge_json_dir(input_path, output_path):
|
||||
directory = Path(input_path)
|
||||
if not directory.is_dir():
|
||||
raise ValueError(f"Not valid PATH: {input_path}")
|
||||
|
||||
seen_ids = set() # برای ردیابی idهای دیدهشده (سریع!)
|
||||
unique_data = [] # فقط دادههای یکتا
|
||||
failed_files = []
|
||||
|
||||
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 not data: # خالی یا None
|
||||
failed_files.append(json_file.name)
|
||||
continue
|
||||
|
||||
# if isinstance(data, dict):
|
||||
# unique_data.append(data)
|
||||
if isinstance(data, list) and isinstance(data[0], dict):
|
||||
for item in data:
|
||||
item_id = item.get("id")
|
||||
if item_id is None:
|
||||
# اگر id نداشت، میتونی تصمیم بگیری: نگه داری یا ردش کنی
|
||||
# اینجا فرض میکنیم فقط مواردی با id معتبر مهم هستند
|
||||
continue
|
||||
if item_id not in seen_ids:
|
||||
seen_ids.add(item_id)
|
||||
unique_data.append(item)
|
||||
else:
|
||||
raise ValueError(f"no list available in this json -> {json_file}")
|
||||
except (json.JSONDecodeError, ValueError, OSError, KeyError, TypeError) as e:
|
||||
print(f"❌ Failed in process '{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=unique_data, path=output_path)
|
||||
print(
|
||||
f"\n💾 Final file saved: {output_path} (Total unique items: {len(unique_data)})"
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"❌ Error in saving final 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)
|
||||
print(f"-- len ids {len(finall_data)}")
|
||||
|
||||
save_orjson(data=finall_data, path=out_path)
|
||||
|
||||
|
||||
def __try_parse_json(value):
|
||||
"""اگر value یک رشته باشد و بتوان آن را به JSON پارس کرد، نسخه پارسشده را برمیگرداند."""
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
# فقط اگر واقعاً JSON بود (نه یک عدد یا کلمه ساده)
|
||||
if isinstance(parsed, (dict, list)):
|
||||
return parsed
|
||||
else:
|
||||
return value # مثلاً اگر رشته "123" بود، نمیخواهیم به عدد تبدیلش کنیم
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return value
|
||||
|
||||
|
||||
def __deep_parse_json_strings(obj):
|
||||
"""به صورت بازگشتی همه رشتههایی که JSON هستند را پارس میکند."""
|
||||
if isinstance(obj, dict):
|
||||
return {
|
||||
key: __deep_parse_json_strings(__try_parse_json(value))
|
||||
for key, value in obj.items()
|
||||
}
|
||||
elif isinstance(obj, list):
|
||||
return [__deep_parse_json_strings(__try_parse_json(item)) for item in obj]
|
||||
else:
|
||||
return obj
|
||||
|
||||
|
||||
def serialize_json_from_str_fields(json_in, out_path=None):
|
||||
if out_path is None:
|
||||
out_path = json_in
|
||||
|
||||
# بارگذاری داده
|
||||
data = load_orjson(json_in)
|
||||
|
||||
# پارس کردن عمیق همه رشتههای JSON
|
||||
cleaned_data = __deep_parse_json_strings(data)
|
||||
|
||||
# ذخیره نتیجه
|
||||
save_orjson(data=cleaned_data, path=out_path)
|
||||
print(f"✅ all done '{out_path}'")
|
||||
|
||||
|
||||
def make_format(in_path, out_path):
|
||||
data = load_orjson(in_path)
|
||||
f_data = []
|
||||
|
||||
for i in data:
|
||||
form = {
|
||||
"id": None,
|
||||
"word": None,
|
||||
"ai_code_version": None,
|
||||
"ai_result": [],
|
||||
}
|
||||
form["id"] = i["id"]
|
||||
form["word"] = i["word"]
|
||||
form["ai_result"] = i["ai_code"]["ai_code"]["result"]
|
||||
form["ai_code_version"] = i["ai_code"]["ai_code_version"]
|
||||
f_data.append(form)
|
||||
|
||||
save_orjson(data=f_data, path=out_path)
|
||||
|
||||
|
||||
# --- نحوه استفاده ---
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.normalize_data
|
||||
if __name__ == "__main__":
|
||||
# ##### یکی کردن تمام بچ های خروجی در یک فایل
|
||||
# merge_json_dir(
|
||||
# input_path= '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/input_data/batch_data',
|
||||
# output_path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/lang_ncw/final_data_translate-word-v1-gemma-3-27b_3.json'
|
||||
# )
|
||||
|
||||
###### ساخت یک proccessed id از فایل نهایی
|
||||
# make_new_proccessed_ids_from_file(
|
||||
# json_in ='/home1/ava3/word_bank_proccess/oss_120b_v1/merged_finall.json',
|
||||
# out_path='/home1/ava3/word_bank_proccess/oss_120b_v1/proccessed_id.json',
|
||||
# )
|
||||
|
||||
# جیسونی کردن تمام فیلد ها
|
||||
# serialize_json_from_str_fields(
|
||||
# json_in='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/merged_1.json',
|
||||
# out_path='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/merged_2.json'
|
||||
# )
|
||||
|
||||
# format finallize
|
||||
# make_format(
|
||||
# in_path='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/data.json',
|
||||
# out_path='/home1/ava3/keyword_simpify_proccess/data_keyword_gemma27/data_f1.json'
|
||||
# )
|
||||
# input_path = "/home1/ava3/word_bank_proccess/oss_120b_v1/merged_finall.json"
|
||||
# data = load_orjson(input_path)
|
||||
# print(f"------{len(data)}-----")
|
||||
# Truley = []
|
||||
# for i in data:
|
||||
# if i['ai_code']['ai_code']['is_correct'] is True : #and i['ai_code']['ai_code']['is_proper_noun'] is True
|
||||
# Truley.append(i)
|
||||
|
||||
# ---------------- filter حقوقی word
|
||||
# input_path = "/home1/ava3/word_bank_proccess/oss_120b_v1/merged_finall.json"
|
||||
# data = load_orjson(input_path)
|
||||
# Truley = []
|
||||
# for item in data:
|
||||
# if "حقوقی" in item['ai_code']['ai_code']['scope'] and item['ai_code']['ai_code']["is_correct"] is True:
|
||||
# Truley.append(item)
|
||||
|
||||
# print(f'Truley {len(Truley)}')
|
||||
# save_orjson(
|
||||
# data=Truley,
|
||||
# path='/home1/ava3/project/aidataparser_test/motaradef_dataset/motaradef.json'
|
||||
# )
|
||||
########################################################################
|
||||
# raw_data = '/home1/ava3/data/mj_qa_section.json'
|
||||
# raw_data = load_orjson(raw_data)
|
||||
# ignore_data = '/home1/ava3/data/ignore_mj_qa_sections.json'
|
||||
# ignore_data = load_orjson(ignore_data)
|
||||
# ignore_data = set(ignore_data)
|
||||
|
||||
# f_data = []
|
||||
# for item in raw_data:
|
||||
# if item['id'] not in ignore_data:
|
||||
# f_data.append(item)
|
||||
|
||||
# print(f'f_data {len(f_data)}')
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/data/valid_mj_qa_sections.json'
|
||||
# )
|
||||
|
||||
# ##########################################################################
|
||||
input_data = load_orjson(
|
||||
"/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/v1_()/merge_all_().json"
|
||||
)
|
||||
v2_data = load_orjson(
|
||||
'/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/v1_()/per_word_327k_magistral_small_2509.json'
|
||||
)
|
||||
print(F'input_data {len(input_data)}')
|
||||
print(F'v2_data {len(v2_data)}')
|
||||
f_data = {}
|
||||
for item in v2_data:
|
||||
new_item = {}
|
||||
result = item["result"]
|
||||
try:
|
||||
result = result.split('(')[1]
|
||||
result = result.split(')')[0]
|
||||
except:
|
||||
print(f"item {item}")
|
||||
break
|
||||
ai_code_version = item["ai_code_version"]
|
||||
ai_code_version = ai_code_version +"_true_word_oss120"
|
||||
|
||||
word = item["word"]
|
||||
_data = input_data.get(word, None)
|
||||
if _data:
|
||||
input_data[word][ai_code_version] = result
|
||||
else:
|
||||
input_data[word] = {
|
||||
ai_code_version : result,
|
||||
}
|
||||
|
||||
print(
|
||||
f"input_data {len(input_data)}"
|
||||
)
|
||||
save_orjson(
|
||||
data=input_data,
|
||||
path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/v1_()/merge_all_().json'
|
||||
)
|
||||
###########################################################################
|
||||
# words1 = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/data/phase1/phase1_1218k_oss_120b.json")
|
||||
|
||||
# f_data = []
|
||||
# for item in words1:
|
||||
# new_item = {}
|
||||
# new_item["word"] = item["word"]
|
||||
# new_item["ai_code_version"] = item["ai_code"]["ai_code_version"]
|
||||
# new_item["is_correct"] = item["ai_code"]["ai_code"]["is_correct"]
|
||||
# new_item["nearest_correct_word"] = item["ai_code"]["ai_code"]["nearest_correct_word"]
|
||||
# new_item["origin"] = item["ai_code"]["ai_code"]["origin"]
|
||||
# new_item["stem"] = item["ai_code"]["ai_code"]["stem"]
|
||||
# new_item["is_proper_noun"] = item["ai_code"]["ai_code"]["is_proper_noun"]
|
||||
# new_item["word_class"] = item["ai_code"]["ai_code"]["word_class"]
|
||||
# new_item["tags"] = item["ai_code"]["ai_code"]["tags"]
|
||||
# new_item["ner_description"] = item["ai_code"]["ai_code"]["ner_description"]
|
||||
# new_item["confidence"] = item["ai_code"]["ai_code"]["confidence"]
|
||||
# new_item["lang"] = item["ai_code"]["ai_code"]["lang"]
|
||||
# new_item["scope"] = item["ai_code"]["ai_code"]["scope"]
|
||||
|
||||
# f_data.append(
|
||||
# new_item
|
||||
# )
|
||||
# print(
|
||||
# f"f_data {len(f_data)}"
|
||||
# )
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/init_mahdi/DataLake/Word/all_data_v1/phase1_1218706_oss_120b.json'
|
||||
# )
|
||||
# ##########################################################################
|
||||
# raw_data = load_orjson('/home1/ava3/data/valid_mj_qa_sections.json')
|
||||
# f_data = []
|
||||
# for item in raw_data:
|
||||
# f_data.append(
|
||||
# {
|
||||
# 'id':item['id'],
|
||||
# 'content':item['content']
|
||||
# }
|
||||
# )
|
||||
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/data/valid_mj_qa_sections_light.json')
|
||||
##########################################################################
|
||||
print(":D")
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
from aiDataParser import AsyncCore
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Any
|
||||
import time
|
||||
|
||||
class Result(BaseModel):
|
||||
result: str
|
||||
# /home2/MODELS/llama4/Llama-4-Scout-17B-16E-Instruct
|
||||
if __name__ == '__main__':
|
||||
start = time.time()
|
||||
ruuner1 = AsyncCore(
|
||||
model_name='gpt-oss-20b',
|
||||
data_path= '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/all_persia_t_and_f.json',
|
||||
output_path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/all_persian_gpt_oss120b',
|
||||
api_url="http://127.0.0.1:8001/v1/",# "http://172.16.29.102:8001/v1/",
|
||||
task_name='word-p2-gpt-oss-20b-testi',
|
||||
output_schema=Result,
|
||||
reasoning_effort='medium',
|
||||
ai_code_version='gptoss120b_p2_med',
|
||||
request_timeout=30,
|
||||
save_number=100,
|
||||
semaphore_number=64,
|
||||
priority=1,
|
||||
)
|
||||
ruuner1.async_eval()
|
||||
end = time.time()
|
||||
|
||||
print(f'Time {end-start:.2f}')
|
||||
print(':D')
|
||||
"""
|
||||
8003
|
||||
gemma-3-27b
|
||||
"""
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.main
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
from aiDataParser import AsyncCore
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Any
|
||||
import time
|
||||
|
||||
class Result(BaseModel):
|
||||
result: str
|
||||
# /home2/MODELS/llama4/Llama-4-Scout-17B-16E-Instruct
|
||||
if __name__ == '__main__':
|
||||
start = time.time()
|
||||
ruuner1 = AsyncCore(
|
||||
model_name='gemma-3-27b',
|
||||
data_path= '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/all_persia_t_and_f.json',
|
||||
output_path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/all_persia_gemma327b/output',
|
||||
api_url="http://127.0.0.1:8003/v1/",# "http://172.16.29.102:8001/v1/",
|
||||
task_name='word-p2-gemma-3-27b',
|
||||
output_schema=Result,
|
||||
reasoning_effort='medium',
|
||||
ai_code_version='gemma327b_p2_med',
|
||||
request_timeout=30,
|
||||
save_number=100,
|
||||
semaphore_number=64,
|
||||
priority=1,
|
||||
)
|
||||
ruuner1.async_eval()
|
||||
end = time.time()
|
||||
|
||||
print(f'Time {end-start:.2f}')
|
||||
print(':D')
|
||||
"""
|
||||
8003
|
||||
gemma-3-27b
|
||||
"""
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.main2
|
||||
Executable
+400
@@ -0,0 +1,400 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
from aiDataParser import AsyncCore
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional, Dict
|
||||
|
||||
|
||||
def load_orjson(path: str | Path):
|
||||
path = Path(path)
|
||||
with path.open("rb") as f:
|
||||
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)
|
||||
)
|
||||
|
||||
###################### len
|
||||
path = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/description_validdata1240000.json"
|
||||
data = load_orjson(path)
|
||||
print(f'path {len(data)}')
|
||||
unique = set([i['word'] for i in data])
|
||||
print(f'unique {len(list(unique))}')
|
||||
######### check
|
||||
# print("[","".join([
|
||||
# "ٔ",
|
||||
# "ٰ",
|
||||
# "ْ",
|
||||
# "",
|
||||
# "_"
|
||||
# ]),"]", sep="")
|
||||
# _path = '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/all_word.json'
|
||||
# total_data = load_orjson(_path)
|
||||
# f_total_data =set()
|
||||
# f_total_char =set()
|
||||
# for i in total_data:
|
||||
# # item = i.split(' ')
|
||||
# # for j in item :
|
||||
# item = i.strip()
|
||||
# if len(item) >1:
|
||||
# f_total_data.add()
|
||||
# f_total_char.update(i)
|
||||
|
||||
# f_total_data = list(f_total_data)
|
||||
# f_total_char = list(f_total_char)
|
||||
# print(
|
||||
# f'f_total_data {len(f_total_data)}',
|
||||
# f'f_total_char {len(f_total_char)}',
|
||||
# sep='\n'
|
||||
# )
|
||||
# f_total_data = sorted(f_total_data, key=lambda i: ord(str(i)[0]) if str(i) else 0)
|
||||
# f_total_data = sorted(f_total_data, key=lambda i: ord(str(i)[0]) if str(i) else 0)
|
||||
# save_orjson(
|
||||
# data=f_total_data,
|
||||
# path=_path,
|
||||
# )
|
||||
# save_orjson(
|
||||
# data=f_total_char,
|
||||
# path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/f_total_char.json",
|
||||
# )
|
||||
######### test and numbering - normalization
|
||||
# import re
|
||||
|
||||
# # o1 ="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/description_data_nor_morakab_verb.json"
|
||||
# # o2 ="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/description_validdata1240000.json"
|
||||
# o3 ="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/validation_description_data.json"
|
||||
# total_data = load_orjson(
|
||||
# "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/description_merge.json"
|
||||
# )
|
||||
|
||||
# f_char = set()
|
||||
# for i in total_data:
|
||||
# f_char.add(i["word"])
|
||||
# f_char.add(i["description"])
|
||||
|
||||
|
||||
# def sort_data3(item):
|
||||
# return int(len(item["description"]))
|
||||
|
||||
# def remove_bracketed(text: str) -> str:
|
||||
# pattern = r"""
|
||||
# \([^)]*\) | \{[^}]*\} | \[[^\]]*\] |
|
||||
# «[^»]*» | “[^”]*” | ‘[^’]*’ |
|
||||
# `[^`]*` | <[^>]*> | '[^']*' | "[^"]*"
|
||||
# """
|
||||
# return re.sub(pattern, '', text, flags=re.VERBOSE | re.UNICODE)
|
||||
|
||||
# chars = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/all_char.json')
|
||||
# # pattern = r"[`\"'{}[\]؟:!0123456789.،\(\)؛,]+"
|
||||
# pattern = f"[{''.join(map(re.escape, chars))}]"
|
||||
|
||||
# def keep_bracket_content(text: str) -> str:
|
||||
# """
|
||||
# متن داخل پرانتزها (یا هر نوع پرانتز دیگری) را نگه میدارد و پرانتزها را حذف میکند.
|
||||
|
||||
# پارامتر:
|
||||
# text (str): متن ورودی
|
||||
|
||||
# خروجی:
|
||||
# str: متن با حذف پرانتزها و نگه داشتن محتوا
|
||||
# """
|
||||
# pattern = r"""
|
||||
# \(([^)]*)\) | # ( ... )
|
||||
# \{([^}]*)\} | # { ... }
|
||||
# \[([^\]]*)\] | # [ ... ]
|
||||
# «([^»]*)» | # « ... »
|
||||
# “([^”]*)” | # “ ... ”
|
||||
# ‘([^’]*)’ | # ‘ ... ’
|
||||
# `([^`]*)` | # ` ... `
|
||||
# <([^>]*)> | # < ... >
|
||||
# '([^']*)' | # ' ... '
|
||||
# "([^"]*)" # " ... "
|
||||
# """
|
||||
# # تابعی که اولین گروه غیر None را برمیگرداند
|
||||
# def repl(match: re.Match) -> str:
|
||||
# # گروههای متشکل از متن داخل پرانتزها
|
||||
# groups = match.groups()
|
||||
# # اولین گروهی که مقدار دارد را برمیگردانیم
|
||||
# return next(g for g in groups if g is not None)
|
||||
|
||||
# return re.sub(pattern, repl, text, flags=re.VERBOSE | re.UNICODE)
|
||||
|
||||
# from typing import List
|
||||
|
||||
# def extract_bracket_content(text: str) -> List[str]:
|
||||
# """
|
||||
# تمام متنهای داخل پرانتزها (یا هر نوع پرانتزی که در الگوی زیر تعریف شده است)
|
||||
# را استخراج میکند و به صورت لیست برمیگرداند.
|
||||
|
||||
# پارامتر:
|
||||
# text (str): متن ورودی
|
||||
|
||||
# خروجی:
|
||||
# List[str]: لیستی از متنهای داخل پرانتزها
|
||||
# """
|
||||
# pattern = r"""
|
||||
# \(([^)]*)\) | # ( ... )
|
||||
# \{([^}]*)\} | # { ... }
|
||||
# \[([^\]]*)\] | # [ ... ]
|
||||
# «([^»]*)» | # « ... »
|
||||
# “([^”]*)” | # “ ... ”
|
||||
# ‘([^’]*)’ | # ‘ ... ’
|
||||
# `([^`]*)` | # ` ... `
|
||||
# <([^>]*)> | # < ... >
|
||||
# '([^']*)' | # ' ... '
|
||||
# "([^"]*)" # " ... "
|
||||
# """
|
||||
# # findall بر تمام گروههای مطابقتی که در pattern تعریف شدهاند، برمیگرداند
|
||||
# # هر گروه یک tuple است؛ ما فقط اولین عضو غیر None را میگیریم
|
||||
# matches = re.findall(pattern, text, flags=re.VERBOSE | re.UNICODE)
|
||||
|
||||
# # تبدیل tuple به لیست متنهای واقعی
|
||||
# contents = []
|
||||
# for match in matches:
|
||||
# # match یک tuple از طول 10 است؛ فقط اولین عضو غیر None را میگیریم
|
||||
# for group in match:
|
||||
# if group: # اگر گروه خالی نباشد
|
||||
# contents.append(group)
|
||||
# break # فقط اولین گروه را میگیریم
|
||||
|
||||
# return contents
|
||||
|
||||
# bracket_texts = set()
|
||||
# for item in total_data:
|
||||
# bracket_texts.update(extract_bracket_content(item.get('description', '')) )
|
||||
|
||||
# f_list = set()
|
||||
# valid_char = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/f_total_char.json")
|
||||
# for item in bracket_texts:
|
||||
# if len(item) > 2:
|
||||
# if all(i in valid_char for i in item ):
|
||||
# valid_word = item.split(" ")
|
||||
# for j in valid_word:
|
||||
# f_list.add(j)
|
||||
|
||||
|
||||
# f_list = list(f_list)
|
||||
# f_list = sorted(f_list, key=len)
|
||||
# print(f'f_list {len(f_list)}')
|
||||
# save_orjson(
|
||||
# data=f_list,
|
||||
# path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/bracket_texts.json",
|
||||
# )
|
||||
# اگر میخواهید فقط اولین متن داخل پرانتز را نگه دارید:
|
||||
# item['description'] = bracket_texts[0] if bracket_texts else ''
|
||||
# # 3. تقسیم متن به کلمات و جمعآوری یکتا
|
||||
# f_list = set()
|
||||
# unvalid = 0
|
||||
# for text in f_char:
|
||||
# cleaned = remove_bracketed(text)
|
||||
# if cleaned != text: unvalid +=1
|
||||
|
||||
# for w in re.split(pattern, cleaned):
|
||||
# w = w.strip()
|
||||
# if len(w) > 1 :
|
||||
# f_list.add(w)
|
||||
|
||||
# f_list = list(f_list)
|
||||
# print(f"f_list {len(f_list)} unvalid{unvalid}")
|
||||
# f_list = sorted(f_list, key=len)
|
||||
|
||||
# save_orjson(
|
||||
# data=f_list,
|
||||
# path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/all_word.json",
|
||||
# )
|
||||
# رشتهها
|
||||
################################### gemma stuff
|
||||
|
||||
|
||||
# class Description(BaseModel):
|
||||
# name: str
|
||||
# description: str
|
||||
|
||||
|
||||
# class Data(BaseModel):
|
||||
# input_description: str
|
||||
# correct_spell: str = "" ######################### only in nor verb
|
||||
# close_description: List[Description]
|
||||
|
||||
|
||||
# class Result(BaseModel):
|
||||
# result: Data
|
||||
|
||||
|
||||
# data1 = "/home1/ava3/init_mahdi/project/aiDataParser/task/q_a_simple/output_phase2/final_data_make-more-knowldege-phase2-gemma-3-27b.json"
|
||||
# 117768 [new_descriptions, validation, word, user_prompt}]
|
||||
# باید از user_prompt داده ورودی داخل `` را بیرون بکشیم
|
||||
# در مورد `{word}` این اطلاعات را دارم `{description}`
|
||||
# new_descriptions
|
||||
# validation
|
||||
# # word
|
||||
# data2 = "/home1/ava3/init_mahdi/project/aiDataParser/task/q_a_simple/output_nor_verb1/final_data_knowldege-gemma-3-27b.json"
|
||||
# # 4167 [Result]
|
||||
# data3 = "/home1/ava3/init_mahdi/project/aiDataParser/task/q_a_simple/output/final_data_knowldege-gemma-3-27b.json"
|
||||
# # 1217790
|
||||
# data4 = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/all_persia_gemma327b/output/final_data_word-p2-gemma-3-27b.json"
|
||||
# # ()
|
||||
# data5 = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/gemma327b/output/final_data_word-p2-gemma-3-27b.json"
|
||||
# # ()
|
||||
# data6 = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/mistral-2509/final_data_word-p2-magistral-small-2509.json"
|
||||
# # ()
|
||||
# # data3 = ""
|
||||
# base_o_path = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data"
|
||||
# temp1 = []
|
||||
# _valid = 0
|
||||
# """
|
||||
# v1 :
|
||||
# - data3
|
||||
# - data2
|
||||
|
||||
|
||||
# """
|
||||
# data_list1 = load_orjson(data1)
|
||||
# print(f'data_list1 {type(data_list1)}')
|
||||
# print(f'data_list1 {len(data_list1)} {data_list1[0]}')
|
||||
|
||||
############# data4
|
||||
|
||||
############# data3
|
||||
# for item in data_list1:
|
||||
# word = item["word"]
|
||||
# result = item["result"]
|
||||
# if isinstance(result, str):
|
||||
# temp1.append({"description": "", "word": word})
|
||||
# # temp1.append(item)
|
||||
# elif isinstance(result, Dict):
|
||||
# temp1.append({"description": result["input_description"], "word": word})
|
||||
# for item in result["close_description"]:
|
||||
# temp1.append({"description": item["description"], "word": item["name"]})
|
||||
# _valid += 1
|
||||
# else:
|
||||
# print(f"Errpr {item}<<")
|
||||
|
||||
# def sort_data3(item):
|
||||
# return int(len(item['description']))
|
||||
|
||||
# temp1 = list(sorted(temp1, key=sort_data3))
|
||||
|
||||
############# data2
|
||||
# for item in data_list1:
|
||||
# word = item['word']
|
||||
# result = item['result']
|
||||
# if isinstance(result, str): pass
|
||||
# elif isinstance(result, Dict):
|
||||
# temp1.append(item)
|
||||
# result = Data.model_validate(result)
|
||||
# _valid += 1
|
||||
# else:
|
||||
# print(
|
||||
# f'Errpr {item}<<'
|
||||
# )
|
||||
import traceback
|
||||
|
||||
# data_list1 = data_list1[:400]
|
||||
############# data1
|
||||
# for item in data_list1:
|
||||
# try:
|
||||
# print(f'')
|
||||
# user_prompt = item['user_prompt'].strip('\n').split("`")[-2]
|
||||
# validation = item['validation']
|
||||
# new_descriptions = item['new_descriptions']
|
||||
# word = item["word"]
|
||||
# temp1.append(
|
||||
# {
|
||||
# "word":word,
|
||||
# "validation" : validation,
|
||||
# "description":user_prompt
|
||||
# }
|
||||
# )
|
||||
# for i in new_descriptions:
|
||||
# temp1.append(
|
||||
# {
|
||||
# "word":word,
|
||||
# "validation" : "unknown",
|
||||
# "description": i
|
||||
# }
|
||||
# )
|
||||
# except:
|
||||
# print(f'item {item}')
|
||||
# traceback.print_exc()
|
||||
|
||||
|
||||
############ save-test
|
||||
# print(f"temp1 {len(temp1)} _valid {_valid}")
|
||||
# save_orjson(data=temp1, path=base_o_path + "/validation_description_data.json")
|
||||
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.finall_data.main
|
||||
################################### get togher
|
||||
# tag = 'gemma27b_p1'
|
||||
# o_path = '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/word_bankv1.json'
|
||||
# input_data1 = load_orjson(
|
||||
# # '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/word_correct2.json'
|
||||
# # "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_correct_stem.json"
|
||||
# # "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/finall_data_verbs.json"
|
||||
# "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/all_word_gemma.json"
|
||||
# )
|
||||
# input_data = set()
|
||||
# for item in input_data1:
|
||||
# input_data.add(
|
||||
# item
|
||||
# )
|
||||
# # verb = dict_item['verb']
|
||||
# # pass_vands = dict_item['pass_vands']
|
||||
# # pish_vands = dict_item['pish_vands']
|
||||
|
||||
# # for item in pish_vands:
|
||||
# # i = item+verb
|
||||
# # input_data.add(i)
|
||||
|
||||
# # for item in pass_vands:
|
||||
# # i = verb+item
|
||||
# # input_data.add(i)
|
||||
|
||||
# input_data = list(input_data)
|
||||
# f_list = load_orjson(
|
||||
# o_path
|
||||
# )
|
||||
# print(f'input_data {len(input_data)}')
|
||||
# print(f'f_list {len(f_list)}')
|
||||
# ff_list = defaultdict(set)
|
||||
# for k, v in f_list.items():
|
||||
# ff_list[k].update(
|
||||
# v['tags']
|
||||
# )
|
||||
|
||||
# for word in input_data:
|
||||
# # if _word :
|
||||
# ff_list[word].add(
|
||||
# tag
|
||||
# )
|
||||
# # else:
|
||||
# # f_list[word] = {
|
||||
# # tag
|
||||
# # }
|
||||
|
||||
# fff_list = {}
|
||||
# for k, v in ff_list.items():
|
||||
# fff_list[k] = list(v)
|
||||
|
||||
|
||||
|
||||
# fff_list = dict(sorted(fff_list.items(),
|
||||
# key=lambda kv: len(kv[1]), reverse=True))
|
||||
|
||||
# save_orjson(
|
||||
# data=fff_list,
|
||||
# # path=o_path,
|
||||
# path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/finall_data/word_bankv_11.json"
|
||||
# )
|
||||
# print(
|
||||
# f'f_list {len(f_list)}',
|
||||
# ":D", sep='\n'
|
||||
# )
|
||||
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.finall_data.main
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def load_orjson(path: str | Path):
|
||||
path = Path(path)
|
||||
with path.open("rb") as f:
|
||||
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)
|
||||
)
|
||||
|
||||
|
||||
# all_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
|
||||
# all_stem = {}
|
||||
# all_nearest_correct_word = {}
|
||||
# valid_lang = {"فارسی", "فارسی باستان"}
|
||||
# print(
|
||||
# [1, 2] == [2, 1]
|
||||
# )
|
||||
# new_dict = {}
|
||||
# for item in all_data:
|
||||
# word = item['word']
|
||||
# is_correct = item['ai_code']['ai_code']['is_correct']
|
||||
# is_proper_noun = item['ai_code']['ai_code']["is_proper_noun"]
|
||||
# langs = item['ai_code']['ai_code']["lang"]
|
||||
|
||||
# stem = item['ai_code']['ai_code']['stem']
|
||||
# nearest_correct_word = item['ai_code']['ai_code']['nearest_correct_word']
|
||||
|
||||
|
||||
# if bool(len(langs) == 1 and langs[0] == "فارسی") or bool(len(langs) == 2 and set(langs) == set(["عربي", "فارسی"]) or set(langs) == set(["عربى", "فارسی"])or set(langs) == set(["عربی", "فارسی"])):
|
||||
# if nearest_correct_word in all_nearest_correct_word.keys():
|
||||
# all_nearest_correct_word[nearest_correct_word] += 1
|
||||
# else:
|
||||
# all_nearest_correct_word[nearest_correct_word] = 1
|
||||
|
||||
# if stem in all_stem.keys():
|
||||
# all_stem[stem] += 1
|
||||
# else:
|
||||
# all_stem[stem] = 1
|
||||
|
||||
# # if is_correct == True and len(langs) == 1 and langs[0] == "فارسی" and is_proper_noun == True:
|
||||
|
||||
# # if is_correct == True:
|
||||
# # word_classes = item['ai_code']['ai_code']['word_class']
|
||||
# # tags = item['ai_code']['ai_code']['tags']
|
||||
# # else:
|
||||
|
||||
|
||||
# print(f'all_data {len(all_data)}')
|
||||
# print(f'all_stem {len(all_stem)}')
|
||||
# print(f'all_nearest_correct_word {len(all_nearest_correct_word)}')
|
||||
|
||||
# f_all_stem = {}
|
||||
# for k, v in all_stem.items():
|
||||
# if v >= 5:
|
||||
# f_all_stem[k] = v
|
||||
|
||||
# # f_all_nearest_correct_word = {}
|
||||
# # for k, v in all_nearest_correct_word.items():
|
||||
# # if v >= 5: # بهترین انتخاب
|
||||
# # f_all_nearest_correct_word[k] = v
|
||||
|
||||
# print(f'f_all_stem {len(f_all_stem)}')
|
||||
|
||||
# sorted_keys = sorted(f_all_stem.items(), key=lambda item: item[1])
|
||||
# save_orjson(
|
||||
# data=sorted_keys, path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_stem2.json'
|
||||
# )
|
||||
|
||||
##################################################### Stem
|
||||
# all_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
|
||||
# nearest_correct_words = {}
|
||||
# for item in all_data:
|
||||
# # word = item['word']
|
||||
# # stem = item['ai_code']['ai_code']['stem']
|
||||
# origin = item['ai_code']['ai_code']['origin']
|
||||
# nearest_correct_word = item['ai_code']['ai_code']['nearest_correct_word']
|
||||
# # is_correct = item['ai_code']['ai_code']['is_correct']
|
||||
# # is_proper_noun = item['ai_code']['ai_code']["is_proper_noun"]
|
||||
# langs = item['ai_code']['ai_code']["lang"]
|
||||
# confidence = item['ai_code']['ai_code']["confidence"]
|
||||
# if bool(len(langs) == 1 and langs[0] == "فارسی") and confidence>= 0.99:
|
||||
# if nearest_correct_word not in nearest_correct_words.keys():
|
||||
# nearest_correct_words[nearest_correct_word] = 1
|
||||
# else:
|
||||
# nearest_correct_words[nearest_correct_word] += 1
|
||||
|
||||
# # if is_correct == True and is_proper_noun == True and bool(len(langs) == 1 and langs[0] == "فارسی"):
|
||||
# # f_data.append(word)
|
||||
|
||||
# # f_data = {}
|
||||
# # for k, v in all_origin.items():
|
||||
# # if
|
||||
# print(f'nearest_correct_words {len(nearest_correct_words)}')
|
||||
# sorted_keys = sorted(nearest_correct_words.items(), key=lambda item: item[1])
|
||||
# save_orjson(
|
||||
# data=sorted_keys,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_nearest_correct_words.json'
|
||||
# )
|
||||
######################### temp
|
||||
# verbs = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_correct_stem.json")
|
||||
# words = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_correct_word.json')
|
||||
# print(
|
||||
# f'words {len(words)}',
|
||||
# f'verbs {len(verbs)}',
|
||||
# )
|
||||
# words = set(words)
|
||||
# verbs = set(verbs.keys())
|
||||
# words = words.union(verbs)
|
||||
# print(
|
||||
# f'words {len(list(words))}',
|
||||
# f'verbs {len(list(verbs))}',
|
||||
# )
|
||||
# save_orjson(
|
||||
# data=list(words),
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/word_correct2.json'
|
||||
# )
|
||||
######## find all پسوند و پیشوند of any stem
|
||||
# all_stem = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_correct_stem.json")
|
||||
# all_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
# all_word = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/f_all_word_list.json")
|
||||
# verbs = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/verb_t2.json")
|
||||
|
||||
# print(f'A: verbs {len(verbs)}')
|
||||
# print(f'A: all_word {len(all_word)}')
|
||||
|
||||
# all_word = set(all_word)
|
||||
# verbs = sorted(verbs, key=lambda x: len(x))
|
||||
|
||||
# v = 0
|
||||
# pass_dict = defaultdict(list)
|
||||
# pish_dict = defaultdict(list)
|
||||
# for word in all_word:
|
||||
# word = word.strip()
|
||||
# for verb in verbs:
|
||||
# verb = verb.strip()
|
||||
# if verb in word:
|
||||
# try:
|
||||
# v +=1
|
||||
# pish_vand, pass_vand = word.split(verb)
|
||||
# if len(pish_vand) > 1:
|
||||
# pish_dict[verb].append(pish_vand)
|
||||
|
||||
# if len(pass_vand) > 1:
|
||||
# pass_dict[verb].append(pass_vand)
|
||||
# break
|
||||
# except:
|
||||
# pass
|
||||
|
||||
|
||||
# print(f'v {v}')
|
||||
# print(f'pish_dict {len(pish_dict)}')
|
||||
# print(f'pass_dict {len(pass_dict)}')
|
||||
|
||||
# pish_dict = dict(sorted(pish_dict.items(), key=lambda item: len(item[1])))
|
||||
# save_orjson(
|
||||
# data=pish_dict,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/pass_pish/pish_dict_t2.json'
|
||||
# )
|
||||
# pass_dict = dict(sorted(pass_dict.items(), key=lambda item: len(item[1])))
|
||||
# save_orjson(
|
||||
# data=pass_dict,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/pass_pish/pass_dict_t2.json'
|
||||
# )
|
||||
########################## Counter pass-pish ##########################
|
||||
# pass_data = load_orjson(
|
||||
# "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/pass_pish/pish_dict_t2.json"
|
||||
# )
|
||||
# counter = defaultdict(set)
|
||||
|
||||
# for k, v in pass_data.items():
|
||||
# for i in v:
|
||||
# counter[k].add(i)
|
||||
|
||||
|
||||
# print(f"counter {len(counter)}")
|
||||
|
||||
# _counter = defaultdict(list)
|
||||
# for k, v in counter.items():
|
||||
# for i in v:
|
||||
# _counter[i].append(k)
|
||||
|
||||
# print(f"_counter {len(_counter)}")
|
||||
|
||||
|
||||
# __counter = defaultdict(list)
|
||||
# for k, v in _counter.items():
|
||||
# if len(v) >= 10:
|
||||
# __counter[k] = v
|
||||
|
||||
# print(f"__counter {len(__counter)}")
|
||||
|
||||
# __counter = dict(sorted(__counter.items(), key=lambda item: len(item[1]), reverse=True))
|
||||
|
||||
# save_orjson(
|
||||
# data=__counter,
|
||||
# path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/pass_pish/counter_piss2_t2.json",
|
||||
# )
|
||||
|
||||
#################################################### مرتب کردن جیسون بر اساس اندازه ولیو ها
|
||||
# pish_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/pass_pish/counter_piss2_t2.json')
|
||||
# print(f'pish_data {len(pish_data)}')
|
||||
# sorted_data = {}
|
||||
# for k, v in pish_data.items():
|
||||
# sorted_data[k] = list(sorted(v, key=len, reverse=True))
|
||||
|
||||
|
||||
# sorted_data = dict(sorted(sorted_data.items(), key=lambda item: len(item[1]), reverse=True))
|
||||
|
||||
# save_orjson(
|
||||
# data=sorted_data,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pish_vands/pish_verb_t2.json'
|
||||
# )
|
||||
#################################################### Merge Data
|
||||
# d1 = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pish_vands/pish_verb_t1.json')
|
||||
# d2 = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pish_vands/pish_verb_t2.json')
|
||||
|
||||
# print(f'd2 t{type(d2)}= {len(d2)}n')
|
||||
# print(f'd1 t{type(d1)}= {len(d1)}n')
|
||||
|
||||
# for k,v in d1.items():
|
||||
# _data = d2.get(k, None)
|
||||
# if _data:
|
||||
# for i in v:
|
||||
# d2[k].append(i)
|
||||
# else:
|
||||
# d2[k] = v
|
||||
|
||||
# counter = defaultdict(set)
|
||||
|
||||
# for k, v in d2.items():
|
||||
# for i in v:
|
||||
# counter[k].add(i)
|
||||
|
||||
|
||||
# print(f"counter {len(counter)}")
|
||||
|
||||
# _counter = defaultdict(list)
|
||||
# for k, v in counter.items():
|
||||
# for i in v:
|
||||
# _counter[i].append(k)
|
||||
|
||||
# print(f"_counter {len(_counter)}")
|
||||
|
||||
# sorted_data = {}
|
||||
# for k, v in _counter.items():
|
||||
# sorted_data[k] = list(sorted(v, key=len, reverse=True))
|
||||
|
||||
|
||||
# sorted_data = dict(sorted(sorted_data.items(), key=lambda item: len(item[1]), reverse=True))
|
||||
|
||||
# save_orjson(
|
||||
# data=sorted_data,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pish_vands/pish_verb_merge12.json'
|
||||
# )
|
||||
################################################### fetch json
|
||||
path = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/merge12_data.json"
|
||||
data = load_orjson(path)
|
||||
save_orjson(
|
||||
data=data,
|
||||
path=path
|
||||
)
|
||||
######################################################################### Refactor1
|
||||
path = "/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/merge12_2_data.json"
|
||||
data = load_orjson(path)
|
||||
UNVALID_PISS = {'می', "نمی"}
|
||||
for item in data:
|
||||
verb = item['verb']
|
||||
pish_vands = item['pass_vands']
|
||||
pish_vands = [i for i in pish_vands if i not in UNVALID_PISS]
|
||||
item['pass_vands'] =pish_vands
|
||||
|
||||
save_orjson(
|
||||
data=data,
|
||||
path=path
|
||||
)
|
||||
################################################### مرتب کردن جیسون نهایی برای (بدون-فاصله _ فاصله _ \u200c)
|
||||
# piss_vand = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pish_vands/pish_verb_merge12.json')
|
||||
# pass_vand = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pass_vands/pass_verb_merge12.json')
|
||||
|
||||
# all_verbs = set()
|
||||
# all_verbs.update(pass_vand.keys())
|
||||
# all_verbs.update(piss_vand.keys())
|
||||
|
||||
# print(
|
||||
# f'piss_vand {len(piss_vand)}',
|
||||
# f'pass_vand {len(pass_vand)}',
|
||||
# f'all_verbs {len(list(all_verbs))}',
|
||||
# sep='\n'
|
||||
# )
|
||||
|
||||
# finall_data = []
|
||||
# for k in all_verbs:
|
||||
# pass_vand_data = pass_vand.get(k, [])
|
||||
# piss_vand_data = piss_vand.get(k, [])
|
||||
# finall_data.append(
|
||||
# {
|
||||
# 'verb' :k,
|
||||
# "pass_vands" :pass_vand_data,
|
||||
# "pish_vands" :piss_vand_data,
|
||||
# }
|
||||
# )
|
||||
# print(f'finall_data {len(finall_data)}')
|
||||
# def count_prefix_suffix(item):
|
||||
# return len(item.get("pish_vands", [])) + len(item.get("pass_vands", []))
|
||||
# sorted_data = sorted(finall_data, key=count_prefix_suffix, reverse=True)
|
||||
|
||||
# save_orjson(
|
||||
# data=finall_data,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/merge12_data.json'
|
||||
# )
|
||||
################################################### مرتب کردن جیسون بر اساس اعضای لیست
|
||||
# data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/merge_12.json')
|
||||
# data = set(data)
|
||||
# data = list(data)
|
||||
# print(f'data {len(data)}')
|
||||
# sorted_data = list(sorted(data, key=len, reverse=True))
|
||||
# save_orjson(
|
||||
# data=sorted_data,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/merge_12.json'
|
||||
# )
|
||||
#################################################### Names
|
||||
# data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/f_all_word_list.json')
|
||||
# true_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
# all_data = set([i["word"] for i in true_data])
|
||||
|
||||
# correct_name_s = set()
|
||||
# v = 0
|
||||
# for i in all_data:
|
||||
# if i.endswith("ها"):
|
||||
# v+=1
|
||||
# single_i = i.replace('ها', '')
|
||||
# if single_i in all_data:
|
||||
# correct_name_s.add(single_i)
|
||||
|
||||
# f_data = set()
|
||||
# for i in true_data:
|
||||
# if len(i['ai_code']['ai_code']["lang"]) ==1 and i['ai_code']['ai_code']["lang"][0] == 'فارسی':
|
||||
# if i['ai_code']['ai_code']["origin"] == i["word"]:
|
||||
# if i["word"] in correct_name_s:
|
||||
# print(f'i["word"] {i["word"]}')
|
||||
# f_data.add(i["word"])
|
||||
|
||||
# f_data = list(f_data)
|
||||
# f_data = list(sorted(f_data, key=len, reverse=True))
|
||||
# print(F'f_data {len(f_data)}')
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/names_1_t1.json'
|
||||
# )
|
||||
|
||||
#################################################### استخراج verb های جدید بر اساس پیشوند و پسوند ها
|
||||
# import re
|
||||
|
||||
# pass_vand = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pass_vands/pass_verb_t1.json")
|
||||
# pish_vand = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/pish_vands/pish_verb_t1.json")
|
||||
# all_word_list = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/f_all_word_list.json")
|
||||
# # all_word_list = all_word_list[:10000]
|
||||
# print(f'all_word_list {len(all_word_list)}')
|
||||
# pass_vands = set([k for k, v in pass_vand.items()])
|
||||
# pish_vands = set([k for k, v in pish_vand.items()])
|
||||
|
||||
# verb_t1 = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/verb_t1.json")
|
||||
# verb_t2 = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/verb_t2.json")
|
||||
# verb_t1 += verb_t2
|
||||
# old_verbs = set(verb_t1)
|
||||
# new_verbs = dict()
|
||||
# for word in all_word_list:
|
||||
# for i1 in pish_vands:
|
||||
# for i2 in pass_vands:
|
||||
# pattern = i1 + r"(.*)" + i2
|
||||
# match = re.search(pattern, word)
|
||||
# if match:
|
||||
# _verb = match.group(1).strip()
|
||||
# _verb = _verb.strip('\u200c')
|
||||
# if _verb not in old_verbs:
|
||||
# if '\u200c' not in _verb and "ها" not in _verb:
|
||||
# if _verb != "" and len(_verb) <= 6 and len(_verb) >= 3:
|
||||
# _new = new_verbs.get(_verb, None)
|
||||
# if _new:
|
||||
# new_verbs[_verb] += 1
|
||||
# else:
|
||||
# new_verbs[_verb] = 1
|
||||
|
||||
# print(f'new_verbs {len(new_verbs)}')
|
||||
# new_verbs = dict(sorted(new_verbs.items(), key=lambda item: item[1], reverse=True))
|
||||
# save_orjson(
|
||||
# data=new_verbs,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/important_data/verbs/verb_t2_1.json'
|
||||
# )
|
||||
####################################################
|
||||
|
||||
|
||||
######## stem ner description
|
||||
# all_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
# f_correct = {}
|
||||
# # stem = item['ai_code']['ai_code']['stem']
|
||||
# # origin = item['ai_code']['ai_code']['origin']
|
||||
# # nearest_correct_word = item['ai_code']['ai_code']['nearest_correct_word']
|
||||
# # ner_description = item['ai_code']['ai_code']['ner_description']
|
||||
# word_class = item['ai_code']['ai_code']['word_class']
|
||||
# all_char.update(word_class)
|
||||
# # is_correct = item['ai_code']['ai_code']['is_correct']
|
||||
# # is_proper_noun = item['ai_code']['ai_code']["is_proper_noun"]
|
||||
# # langs = item['ai_code']['ai_code']["lang"]
|
||||
# # confidence = item['ai_code']['ai_code']["confidence"]
|
||||
# # if bool(len(langs) == 1 and langs[0] == "فارسی") and confidence>= 0.99:
|
||||
# # if nearest_correct_word not in nearest_correct_words.keys():
|
||||
# # nearest_correct_words[nearest_correct_word] = 1
|
||||
# # else:
|
||||
# # nearest_correct_words[nearest_correct_word] += 1
|
||||
|
||||
# # if is_correct == True and is_proper_noun == True and bool(len(langs) == 1 and langs[0] == "فارسی"):
|
||||
# # f_data.append(word)
|
||||
# print(f'word_class {len(list(all_char))}')
|
||||
# save_orjson(
|
||||
# data=list(all_char),
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_word_class.json'
|
||||
# )
|
||||
##################################################### Stem
|
||||
# all_correct_stem = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_correct_stem.json')
|
||||
# all_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
# all_correct_stem = {k:{'StemRepeat':v} for k, v in all_correct_stem.items()}
|
||||
|
||||
# i_word = 0
|
||||
# for item in all_data:
|
||||
# word = item['word']
|
||||
# langs = item['ai_code']['ai_code']["lang"]
|
||||
# stem = item['ai_code']['ai_code']['stem']
|
||||
# is_correct = item['ai_code']['ai_code']['is_correct']
|
||||
# if is_correct == True and len(langs) == 1 and langs[0] == "فارسی":
|
||||
# if stem in all_correct_stem.keys():
|
||||
# _data = all_correct_stem[stem]
|
||||
# words = _data.get('Words', None)
|
||||
# if words:
|
||||
# _data['Words'].append(word)
|
||||
# else:
|
||||
# _data['Words'] = [word]
|
||||
# i_word += 1
|
||||
|
||||
# print(f'i_word {i_word}')
|
||||
|
||||
# save_orjson(
|
||||
# data=all_correct_stem,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/t1.json'
|
||||
# )
|
||||
|
||||
|
||||
print(':D')
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.make_data.main
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def load_orjson(path: str | Path):
|
||||
path = Path(path)
|
||||
with path.open("rb") as f:
|
||||
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)
|
||||
)
|
||||
|
||||
|
||||
###############################################
|
||||
|
||||
add_200c = [
|
||||
"خواهید",
|
||||
"خواهند",
|
||||
"خواهیم",
|
||||
"خواهد",
|
||||
"خواهی",
|
||||
"خواهم",
|
||||
"می",
|
||||
"نخواهند"
|
||||
]
|
||||
|
||||
add_space = [
|
||||
"خواهید",
|
||||
"خواهند",
|
||||
"خواهیم",
|
||||
"خواهد",
|
||||
"خواهی",
|
||||
"خواهم",
|
||||
"می",
|
||||
"نخواهند"
|
||||
]
|
||||
|
||||
f_1 = set()
|
||||
f_2 = set()
|
||||
u200 = "\u200c"
|
||||
space = " "
|
||||
|
||||
for item in add_200c:
|
||||
_item = item.strip(" ")
|
||||
_item = item.strip("\u200c")
|
||||
f_1.add(_item + u200)
|
||||
|
||||
for item in add_space:
|
||||
_item = item.strip(" ")
|
||||
_item = item.strip("\u200c")
|
||||
f_2.add(_item + space)
|
||||
|
||||
for item in add_space:
|
||||
_item = item.strip(" ")
|
||||
_item = item.strip("\u200c")
|
||||
f_1.add(_item)
|
||||
|
||||
|
||||
ff_f = f_1.union(f_2)
|
||||
ff_f = list(ff_f)
|
||||
print(f"ff_f {len(ff_f)}")
|
||||
|
||||
ff_f = list(sorted(ff_f, key=len, reverse=True))
|
||||
|
||||
print(f"ff_f {len(ff_f)}")
|
||||
|
||||
save_orjson(
|
||||
data=ff_f,
|
||||
path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/aaa_temp.json",
|
||||
)
|
||||
print(":D")
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.make_data.main_sub
|
||||
+3801
File diff suppressed because it is too large
Load Diff
+118
@@ -0,0 +1,118 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
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 get_word(text:str):
|
||||
if len(text)>0:
|
||||
word = text.split('(')[-1]
|
||||
word = word.split(')')[0]
|
||||
return word
|
||||
|
||||
# merge_data = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/merge1.json")
|
||||
# input_data = load_orjson("/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/gemma327b/output/final_data_word-p2-gemma-3-27b.json")
|
||||
|
||||
# print(f"merge_data {len(merge_data)}")
|
||||
# print(f"input_data {len(input_data)}")
|
||||
|
||||
# for dict_item in input_data:
|
||||
# temp_dict = {}
|
||||
# word = dict_item['word']
|
||||
# temp_dict['gemma3-27b'] = get_word(dict_item['result'])
|
||||
# merge_data[word].update(temp_dict)
|
||||
|
||||
# print(f"f_data {len(merge_data)}")
|
||||
# save_orjson(
|
||||
# data=merge_data, path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/merge2.json"
|
||||
# )
|
||||
#########################################################
|
||||
all_correct_stem = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/make_data/all_correct_stem.json')
|
||||
true_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/oss_120b_v1/true_word.json')
|
||||
|
||||
all_lang = set()
|
||||
|
||||
valid_word = set()
|
||||
valid_lang = {"فارسی", "فارسی باستان"}
|
||||
for item in all_data:
|
||||
langs = set(item['ai_code']['ai_code']['lang'])
|
||||
valid_list = langs - valid_lang
|
||||
if len(list(valid_list)) == 0:
|
||||
valid_word.add(
|
||||
item['word']
|
||||
)
|
||||
# else:
|
||||
# print(
|
||||
# f'valid_list {valid_list}'
|
||||
# )
|
||||
|
||||
print(f'valid_word {len(list(valid_word))}')
|
||||
save_orjson(
|
||||
data=list(valid_word),
|
||||
path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/all_word_persian.json'
|
||||
)
|
||||
#########################################################
|
||||
# per_word = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/t1.json')
|
||||
# true_word = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/merge2.json')
|
||||
|
||||
# print(f'per_word {len(per_word)}')
|
||||
# print(f'true_word {len(true_word)}')
|
||||
# per_word = set(per_word)
|
||||
# print(f'per_word {len(list(per_word))}')
|
||||
# f_dict = {}
|
||||
# for k,v in true_word.items():
|
||||
# if k in per_word:
|
||||
# f_dict[k] = v
|
||||
# print(f'f_dict {len(f_dict)}')
|
||||
# save_orjson(
|
||||
# data=f_dict,
|
||||
# path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/all_per.json"
|
||||
# )
|
||||
#########################################################
|
||||
# def is_correct(t1, t2, t3):
|
||||
# t1_ = ''
|
||||
# t2_ = ''
|
||||
# t3_ = ''
|
||||
# unvalid = ' \u200c'
|
||||
|
||||
# for i in t1:
|
||||
# if i not in unvalid:
|
||||
# t1_ += i
|
||||
|
||||
# for i in t2:
|
||||
# if i not in unvalid:
|
||||
# t2_ += i
|
||||
|
||||
# for i in t3:
|
||||
# if i not in unvalid:
|
||||
# t3_ += i
|
||||
|
||||
# return bool(bool(t1_==t2_) and bool(t3_==t2_))
|
||||
|
||||
# per_all_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/all_per.json')
|
||||
# f_data = {}
|
||||
# for k ,v in per_all_data.items():
|
||||
# if is_correct(v["gemma3-27b"], k,v["gemma3-27b"]):
|
||||
# f_data[k]=v
|
||||
|
||||
# print(f'f_data {len(f_data)}')
|
||||
# save_orjson(
|
||||
# data=f_data,
|
||||
# path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/f_per.json'
|
||||
# )
|
||||
|
||||
|
||||
#########################################################
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.phase2_word.normalize_data
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
import os
|
||||
import json
|
||||
import orjson
|
||||
import tiktoken
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
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 formatter(item:Dict):
|
||||
word = item['word']
|
||||
# nearest_correct_word = item['nearest_correct_word']
|
||||
# is_correct = item['is_correct']
|
||||
return f'در دستورزبان عربی ({word}) صحیح است.'
|
||||
# return f'در دستورزبان فارسی ({word}) صحیح است.'
|
||||
# if is_correct:
|
||||
# return f'در زبان فارسی ({word}) صحیح است.'
|
||||
# else:
|
||||
# if nearest_correct_word != "":
|
||||
# return f'در زبان فارسی ({word}) صحیح نیست و شکل صحیح اش ({nearest_correct_word})'
|
||||
# else:
|
||||
# return f'در زبان فارسی ({word}) صحیح نیست و شکل صحیح ندارد.'
|
||||
|
||||
|
||||
def make_data_stream_token(all_data):
|
||||
api_batch = []
|
||||
for item in all_data:
|
||||
api_batch.append(
|
||||
{
|
||||
"id": item.get("id"),
|
||||
"user_prompt": formatter(item),
|
||||
"system_prompt": SPELLING_PROMPT,
|
||||
"word": item["word"],
|
||||
}
|
||||
)
|
||||
return api_batch
|
||||
|
||||
|
||||
|
||||
USER_PROMPT = '''
|
||||
Input Word : {word}
|
||||
'''
|
||||
|
||||
SYSTEM_PROMPT_V2 = '''**Role**:
|
||||
|
||||
You are persian & arabic word validation Expert with a special focus on Persian (Farsi).
|
||||
|
||||
**Task**:
|
||||
|
||||
Given a single input string (word), analyze it and determine:
|
||||
(A)- if correct in persian fill `is_correct` == true and lang == `persian`.
|
||||
(B)- if correct in arabic fill `is_correct` == true and lang == `arabic`.
|
||||
(C)- if not corrct in persian but there is a word close to this input word in persian and that is correct put in the field `nearest_correct_word` and fill `is_correct` == false and lang == `persian`.
|
||||
|
||||
return a structured result with the following schema:
|
||||
```JSON
|
||||
{
|
||||
"is_correct": "bool <true | false>",
|
||||
"nearest_correct_word": "string",
|
||||
"lang": "string"
|
||||
}
|
||||
```
|
||||
|
||||
**Validation Rules** (VERY IMPORTANT)
|
||||
|
||||
The Word must be Grammatically correct.
|
||||
If there is any doubt, return is_correct = false.
|
||||
words must be in the Standard language form, not slang, not broken, not phonetic guessing, not Nonsense & Partial.
|
||||
Inputs like [`ار`, `تس`, `کب`] Must be treated as incorrect, even if they could resemble:
|
||||
- A letter name in another language
|
||||
- A fragment of a real word
|
||||
- Other Languages.
|
||||
DO NOT guess meanings. DO NOT infer letters.
|
||||
|
||||
**Nearest Correct Word**
|
||||
|
||||
Only provide nearest_correct_word if:
|
||||
There is a very obvious and minimal edit-distance correction
|
||||
Otherwise return an empty string "".
|
||||
Plural & Zero-Width Non-Joiner (ZWNJ) Handling
|
||||
The following must be treated as correct Persian words:
|
||||
مهدیها
|
||||
مهدی\u200cها
|
||||
|
||||
Use:
|
||||
"persian" for Persian
|
||||
"arabic" for Arabic
|
||||
"unknown" if the word is incorrect or nonsense.
|
||||
|
||||
**Output Rules**
|
||||
|
||||
Output ONLY a valid Json object
|
||||
No explanations
|
||||
No extra text
|
||||
No markdown
|
||||
No assumptions
|
||||
|
||||
**Examples (for internal reasoning only)**
|
||||
|
||||
Input | is_correct | nearest_correct_word | lang
|
||||
مهدی ها | true | مهدی ها | persian
|
||||
مهدی\u200cها | true | مهدی\u200cها | persian
|
||||
ار | false | "" | unknown
|
||||
cta | false | cat | unknown
|
||||
سلامم | false | سلام | persian
|
||||
'''
|
||||
|
||||
SYS_PROMPT_STREAM = '''**Role**:
|
||||
You are Game-Player and have to Play with User and Win the Game.
|
||||
|
||||
**Rules**:
|
||||
Repeat the User's input whatever it was wiyhout **changing**, **adding** or **deleting** even a **single character**.
|
||||
Repeat Exact input.
|
||||
|
||||
**Example**:
|
||||
input: سلام خوبی؟
|
||||
output: سلام خوبی؟
|
||||
'''
|
||||
|
||||
|
||||
SPELLING_PROMPT = '''**Role**:
|
||||
شما یک ویراستار و متخصص تصحیح غلط های املایی هستید
|
||||
|
||||
**Task**:
|
||||
The Input Is a Sentence And You Have a Duty to Correct The Grammatically & Shaply Mistaktes In it WITH CHANGE ONLY WORD IN THE () to Have Meaningfull Sentense at Last With Minimum Changes.
|
||||
***Do Not Change Any Other WORD***
|
||||
WithOut Change The Structure Of Sentence And Only Change WORD In (), To have meaningfull and correct Sentence in terms of Meaning.
|
||||
Only the Incorrect Word In the () should be Corrected to Have the Exact Correct Meaning.
|
||||
No External Knowledge Or Any Grammatically Changes Or adding & Deleting Word OutSide the WORD.
|
||||
|
||||
**Important-Note**:
|
||||
WORD Is Not Token Not Conjunction
|
||||
|
||||
**Example**:
|
||||
Input :
|
||||
`کلمه (چکمهی) صحیح است`
|
||||
Ouput :
|
||||
`کلمه (چکمه) صحیح است`'''
|
||||
|
||||
SPELLING_PROMPT_ARABIC = '''**Role**:
|
||||
شما یک ویراستار و متخصص تصحیح غلط های املایی هستید
|
||||
|
||||
**Task**:
|
||||
The Input Is a Sentence And You Have a Duty to Correct The Grammatically & Shaply Mistaktes In it WITH CHANGE ONLY WORD IN THE () to Have Meaningfull Sentense at Last With Minimum Changes.
|
||||
***Do Not Change Any Other WORD***
|
||||
WithOut Change The Structure Of Sentence And Only Change WORD In (), To have meaningfull and correct Sentence in terms of Meaning.
|
||||
Only the Incorrect Word In the () should be Corrected to Have the Exact Correct Meaning.
|
||||
No External Knowledge Or Any Grammatically Changes Or adding & Deleting Word OutSide the WORD.
|
||||
|
||||
**Important-Note**:
|
||||
WORD Is Not Token Not Conjunction
|
||||
|
||||
**Example**:
|
||||
Input :
|
||||
`کلمه (چکمهی) صحیح است`
|
||||
Ouput :
|
||||
`کلمه (چکمه) صحیح است`'''
|
||||
|
||||
word_list = load_orjson(
|
||||
"/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/phase2_word/merge/all_word_persian.json"
|
||||
)
|
||||
|
||||
word_list = [{'id':str(i), 'word':item } for i, item in enumerate(word_list, start=1)]
|
||||
word_list = make_data_stream_token(word_list)
|
||||
|
||||
save_orjson(
|
||||
path="/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/all_persia_t_and_f.json",
|
||||
data=word_list
|
||||
)
|
||||
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.word_v2.report_article.main_create
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
from aiDataParser import StreamAsyncCore, load_orjson, save_orjson
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
import time, asyncio
|
||||
|
||||
async def get_stream_to_normal_list(
|
||||
_item,
|
||||
_reasoning_effort,
|
||||
_temperature,
|
||||
_top_p,
|
||||
_max_token,
|
||||
):
|
||||
f_result = []
|
||||
async for chunk in streamer.single_async_item_stream(
|
||||
item=_item,
|
||||
reasoning_effort=_reasoning_effort,
|
||||
temperature=_temperature,
|
||||
top_p=_top_p, max_token=_max_token,
|
||||
):
|
||||
f_result.append(chunk)
|
||||
|
||||
return f_result
|
||||
|
||||
_max_token=None
|
||||
_reasoning_effort = "medium"
|
||||
_temperature = 0.3
|
||||
_top_p = 0.9
|
||||
_model_name='gemma-3-27b'# 'gpt-oss-120b' # 'gemma-3-27b'
|
||||
_api_url="http://127.0.0.1:8003/v1/" # "http://172.16.29.102:8001/v1/" # "http://127.0.0.1:8003/v1/"
|
||||
_task_name='word-gemma-3-27b'
|
||||
_ai_code_version='gemma_3_27b_medv1'
|
||||
|
||||
streamer = StreamAsyncCore(
|
||||
model_name=_model_name,
|
||||
task_name=_task_name,
|
||||
api_url=_api_url,
|
||||
output_schema=None,
|
||||
data_path=None,
|
||||
output_path=None,
|
||||
reasoning_effort=_reasoning_effort,
|
||||
max_token=_max_token,
|
||||
temperature = _temperature,
|
||||
top_p = _top_p,
|
||||
ai_code_version=_ai_code_version,
|
||||
request_timeout=30, # ثانیه
|
||||
api_key="EMPTY",
|
||||
save_number=2,
|
||||
semaphore_number=10,
|
||||
)
|
||||
|
||||
|
||||
FORMATTER_PRMPT = """Format your response as plain, clean, line-by-line text—no bullet points, no markdown lists, no numbering, and no extra formatting. Each idea or statement should appear on its own line, separated by a single newline. Keep the content unchanged; only improve readability through consistent line breaks."""
|
||||
|
||||
|
||||
C_TYPE_SYSTEM = """
|
||||
شما یک متخصص حقوقی و قانونی هستید به نام «قانونیار».
|
||||
هویت شما: مثل یک قانوندان باتجربه، دقیق، مودب و مشتاق کمک کردن به افراد در فهم مسائل حقوقی و قانونی.
|
||||
|
||||
در این مرحله، وظیفه شما «تشخیص نوع پیام» است؛ اما باید یک دلیل کوتاه (answer) بدهید
|
||||
که لحنش مثل لحن یک وکیل مهربان و حامی باشد.
|
||||
|
||||
برچسب خروجی فقط یکی از این موارد است:
|
||||
- legal_question
|
||||
- greeting
|
||||
- other
|
||||
|
||||
تعریفها:
|
||||
1. legal_question: هر پرسش یا متن مرتبط با قوانین، مقررات، دادگاه، وکالت، قرارداد، مالیات، ارث، نکاح و طلاق، شکایت، چک، سفته، ثبت شرکت، حقوق کار و هر موضوع مشابه.
|
||||
2. greeting: پیامهای غیرحقوقی شامل سلام، معرفی، احوالپرسی، تشکر، خداحافظی.
|
||||
3. other: پیامهایی که خارج از دو دسته بالا قرار میگیرند.
|
||||
|
||||
نکات مهم:
|
||||
- answer باید بسیار کوتاه باشد (حداکثر دو خط).
|
||||
- اگر پیام حتی کمی رنگوبوی حقوقی داشته باشد، answer را به سمت توضیح حقوقی ببرید.
|
||||
- در حالت greeting با لحن رسمی و دوستانه یک قانون شناس پاسخ بدهید.
|
||||
- در حالت other، در عین محترمانهگفتن اینکه پیام حقوقی نیست، سعی کنید یک زاویهٔ حقوقی احتمالی مطرح کنید تا راه کمک باز بماند.
|
||||
|
||||
خروجی شما حتماً باید شامل دو فیلد باشد:
|
||||
label: یکی از سه برچسب
|
||||
answer: توضیح کوتاه، دوستانه، مودب و با لحن یک قانون بلد حامی
|
||||
|
||||
خروجی فقط JSON باشد.
|
||||
""" +FORMATTER_PRMPT
|
||||
|
||||
C_TYPE_ASSIST = """
|
||||
### Example 1:
|
||||
input:
|
||||
"عین کلی"
|
||||
output:
|
||||
{
|
||||
"label": "legal_question",
|
||||
"answer": "موضوع شما به یکی از مفاهیم مهم حقوق مدنی مربوط میشود و با کمال میل راهنماییتان میکنم."
|
||||
}
|
||||
|
||||
### Example 2:
|
||||
input:
|
||||
"طرز تهیه ماست"
|
||||
output:
|
||||
{
|
||||
"label":"other",
|
||||
"answer":"موضوع شما ماهیت حقوقی ندارد، اما اگر دغدغهتان مرتبط با استاندارد یا مسئولیت تولید باشد میتوانم به شما کمک کنم، می شود سوال خود را بهتر و کامل تر بپرسید؟ میخواهم دقیق بدانم چه قسمتی از موارد حقوقی تولید ماست رو میخواهید بدونید"
|
||||
}
|
||||
|
||||
### Example 3:
|
||||
input:
|
||||
"سلام، تو کی هستی؟"
|
||||
output:
|
||||
{
|
||||
"label":"greeting",
|
||||
"answer":"سلام و ارادت؛ من قانونیار هستم، یک مدل هوش مصنوعی آموزش دیده در قوانین جمهوری اسلامی ایران و البته همراه شما برای هر پرسش حقوقی."
|
||||
}
|
||||
""" +FORMATTER_PRMPT
|
||||
|
||||
Spelling_PROMPT = '''**Role**:
|
||||
شما یک ویراستار و متخصص تصحیح غلط های املایی هستید
|
||||
|
||||
**Task**:
|
||||
The Input Is a Sentence And You Have a Duty to Correct The Grammatically & Shaply Mistaktes In it WITH CHANGE ONLY WORD IN THE () to Have Meaningfull Sentense at Last With Minimum Changes.
|
||||
***Do Not Change Any Other WORD***
|
||||
WithOut Change The Structure Of Sentence And Only Change WORD In (), To have meaningfull and correct Sentence in terms of Meaning.
|
||||
Only the Incorrect Word In the () should be Corrected to Have the Exact Correct Meaning.
|
||||
No External Knowledge Or Any Grammatically Changes Or adding & Deleting Word OutSide the WORD.
|
||||
|
||||
**Important-Note**:
|
||||
WORD Is Not Token Not Conjunction
|
||||
|
||||
**Example**:
|
||||
Input :
|
||||
`کلمه (چکمهی) صحیح است`
|
||||
Ouput :
|
||||
`کلمه (چکمه) صحیح است`
|
||||
``
|
||||
'''
|
||||
input_data = load_orjson('/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/138_v1_prompt.json')
|
||||
input_data = input_data[:11]
|
||||
i2_data = [
|
||||
'فیزیولوژیکهایشان',
|
||||
"آهستهآمدنیترینم",
|
||||
"تریدی",
|
||||
"دوجو",
|
||||
"دوافع",
|
||||
"لولاء",
|
||||
"شنفی",
|
||||
"خاتل",
|
||||
"زوکو",
|
||||
"سیحان",
|
||||
"تیلکا",
|
||||
]
|
||||
t1_data = [
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (میشود) صحیح نیست و شکل صحیح اش (میشود)",
|
||||
"word": "میشود"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (میشود) صحیح است و شکل صحیح اش (میشود).",
|
||||
"word": "میشود"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (وتقدیر) صحیح نیست و شکل صحیح اش (و تقدیر)",
|
||||
"word": "وتقدیر"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (بلمانع) صحیح است",
|
||||
"word": "بلمانع"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (فیزیولوژیکهایشان) صحیح نیست و شکل صحیح اش (فیزیولوژیکهایشان)",
|
||||
"word": "فیزیولوژیکهایشان"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (آهستهآمدنیترینم) صحیح نیست و شکل صحیح اش (آهستهآمدنیترینم)",
|
||||
"word": "آهستهآمدنیترینم"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (چک) صحیح است.",
|
||||
"word": "چک"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (دوجو) صحیح است.",
|
||||
"word": "دوجو"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (بیاساسترین) صحیح نیست و شکل صحیح اش (بیاساسترین)",
|
||||
"word": "بیاساسترین"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (کنداکتور) صحیح است.",
|
||||
"word": "کنداکتور"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (نظافة) صحیح نیست و شکل صحیح اش (نظافت)",
|
||||
"word": "نظافة"
|
||||
},
|
||||
{
|
||||
"user_prompt": "در زبان فارسی (پشتسرگذاشتهترینش) صحیح نیست و شکل صحیح اش (پشتسرگذاشتهترین)",
|
||||
"word": "پشتسرگذاشتهترینش"
|
||||
},
|
||||
]
|
||||
|
||||
f_list = []
|
||||
for _i, i_item in enumerate(input_data, start=1):
|
||||
|
||||
_result = asyncio.run(
|
||||
streamer.single_async_item(
|
||||
item={
|
||||
"system_prompt":Spelling_PROMPT,
|
||||
# "assistant_prompt":C_TYPE_ASSIST,
|
||||
# 'user_prompt':' میشه یه توضیح کامل بهم بدی در مورد ضعف عضلانی در قسمت شانه سمت راست من بهم اطلاعات بدی ؟ خیلی واضح درد دارم و نمیدونم چطوری مشکل رو حل کنم یا چه حرکات کششی بهتره ابرای اینکه این قمست از بدنم دیگه درد نکنه چه ورزش ها و حرکات کششی مناسب من هست ؟'
|
||||
'user_prompt': i_item['user_prompt'] # f'درباره {i_item} تو چه میدانی ؟',
|
||||
},
|
||||
reasoning_effort=_reasoning_effort,
|
||||
temperature=_temperature,
|
||||
top_p=_top_p,
|
||||
max_token=_max_token,
|
||||
)
|
||||
)
|
||||
result = {}
|
||||
result['finall'] = _result
|
||||
result['word'] = i_item['word']
|
||||
result['user_prompt'] = i_item['user_prompt']
|
||||
print(f'--- {_i}')
|
||||
f_list.append(result)
|
||||
|
||||
save_orjson(
|
||||
path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/spell_check_gemma_t5.json',
|
||||
data=f_list,
|
||||
)
|
||||
|
||||
print(':D')
|
||||
# if __name__ == '__main__':
|
||||
|
||||
|
||||
# in_data = load_orjson(
|
||||
# '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/138_v1_prompt.json'
|
||||
# )
|
||||
# in_data = in_data[:5]
|
||||
# f_list = []
|
||||
# for i, item in enumerate(in_data, start=1):
|
||||
# _item = {
|
||||
# "user_prompt":item['user_prompt'],
|
||||
# "system_prompt":item['system_prompt'],
|
||||
# }
|
||||
|
||||
# f_result = asyncio.run(
|
||||
# get_stream_to_normal_list(
|
||||
# _item,
|
||||
# _reasoning_effort,
|
||||
# _temperature,
|
||||
# _top_p,
|
||||
# _max_token,
|
||||
# )
|
||||
# )
|
||||
|
||||
|
||||
# f_list.append(
|
||||
# {
|
||||
# "id" :item['id'],
|
||||
# "word":item['word'],
|
||||
# "model_name":_model_name,
|
||||
# "reasoning_effort":_reasoning_effort,
|
||||
# "result":f_result,
|
||||
# "user_prompt":item['user_prompt'],
|
||||
# "mode":'NoneStream',
|
||||
# }
|
||||
# )
|
||||
# print(f'---{i}/{len(in_data)}---')
|
||||
|
||||
# save_orjson(
|
||||
# data=f_list,
|
||||
# path=f'/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/step1.json'
|
||||
# )
|
||||
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.word_v2.report_article.main_run
|
||||
Executable
+258
@@ -0,0 +1,258 @@
|
||||
import os
|
||||
import json
|
||||
from pydantic import BaseModel
|
||||
import orjson
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
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 make_data(all_data):
|
||||
api_batch = []
|
||||
for item in all_data:
|
||||
|
||||
api_batch.append(
|
||||
{
|
||||
"id": str(item.get("id")),
|
||||
"user_prompt": USER_PROMPT.format(word=item['word']),
|
||||
"system_prompt": SYSTEM_PROMPT_V2,
|
||||
"assistant_prompt": None,
|
||||
"word":item['word'],
|
||||
}
|
||||
)
|
||||
return api_batch
|
||||
|
||||
USER_PROMPT = '''
|
||||
Input Word : {word}
|
||||
'''
|
||||
|
||||
SYSTEM_PROMPT_V1 = '''**Role**:
|
||||
You are a very strict persian & arabic word validation engine with a special focus on Persian (Farsi).
|
||||
You must prioritize linguistic correctness, standard spelling, and grammatical validity over guesswork.
|
||||
|
||||
**Task**:
|
||||
Given a single input string (word), analyze it and return a structured result with the following schema:
|
||||
```JSON
|
||||
{
|
||||
"is_correct": "bool <true | false>",
|
||||
"nearest_correct_word": "string",
|
||||
"lang": "string"
|
||||
}
|
||||
```
|
||||
|
||||
🔒 **Validation Rules** (VERY IMPORTANT)
|
||||
|
||||
Extreme Strictness
|
||||
Only mark is_correct = true if the input is:
|
||||
A real, standard, dictionary-valid word
|
||||
Correctly spelled
|
||||
Grammatically acceptable as a standalone word
|
||||
If there is any doubt, return is_correct = false.
|
||||
Persian (Farsi) Priority
|
||||
Persian words must be:
|
||||
Standard Persian (فارسی معیار)
|
||||
Not slang, not broken, not phonetic guessing
|
||||
Random letter combinations are always incorrect.
|
||||
Nonsense & Partial Tokens
|
||||
|
||||
**Inputs like**:
|
||||
- ار
|
||||
- تس
|
||||
- بگ
|
||||
|
||||
Must be treated as incorrect, even if they could resemble:
|
||||
A letter name in another language
|
||||
A fragment of a real word
|
||||
DO NOT guess meanings. DO NOT infer letters.
|
||||
Other Languages
|
||||
If the word is 100% correct in another language (e.g. English, Arabic, French):
|
||||
Set is_correct = true
|
||||
Set lang to the detected language (e.g. "en", "ar")
|
||||
If not 100% certain → mark as incorrect.
|
||||
Nearest Correct Word
|
||||
Only provide nearest_correct_word if:
|
||||
There is a very obvious and minimal edit-distance correction
|
||||
Otherwise return an empty string "".
|
||||
Plural & Zero-Width Non-Joiner (ZWNJ) Handling
|
||||
The following must be treated as correct Persian words:
|
||||
مهدیها
|
||||
مهدی\u200cها
|
||||
|
||||
Differences caused by:
|
||||
Half-space (ZWNJ)
|
||||
Unicode normalization
|
||||
Must NOT cause an error.
|
||||
Language Field (lang)
|
||||
|
||||
Use:
|
||||
"fa" for Persian
|
||||
"en" for English
|
||||
"ar" for Arabic
|
||||
"unknown" if the word is incorrect or nonsense
|
||||
|
||||
🧪 **Output Rules**
|
||||
Output ONLY a valid WordV2 object
|
||||
No explanations
|
||||
No extra text
|
||||
No markdown
|
||||
No assumptions
|
||||
|
||||
🔍 Examples (for internal reasoning only)
|
||||
Input | is_correct | nearest_correct_word | lang
|
||||
مهدیها | true | مهدیها | fa
|
||||
مهدی\u200cها | true | مهدیها | fa
|
||||
ار | false | "" | unknown
|
||||
cat | true | cat | en
|
||||
cta | false | cat | en
|
||||
سلامم | false | سلام | fa
|
||||
'''
|
||||
|
||||
|
||||
SYSTEM_PROMPT_V2 = '''**Role**:
|
||||
|
||||
You are persian & arabic word validation Expert with a special focus on Persian (Farsi).
|
||||
|
||||
**Task**:
|
||||
|
||||
Given a single input string (word), analyze it and determine:
|
||||
(A)- if correct in persian fill `is_correct` == true and lang == `persian`.
|
||||
(B)- if correct in arabic fill `is_correct` == true and lang == `arabic`.
|
||||
(C)- if not corrct in persian but there is a word close to this input word in persian and that is correct put in the field `nearest_correct_word` and fill `is_correct` == false and lang == `persian`.
|
||||
|
||||
return a structured result with the following schema:
|
||||
```JSON
|
||||
{
|
||||
"is_correct": "bool <true | false>",
|
||||
"nearest_correct_word": "string",
|
||||
"lang": "string"
|
||||
}
|
||||
```
|
||||
|
||||
**Validation Rules** (VERY IMPORTANT)
|
||||
|
||||
The Word must be Grammatically correct.
|
||||
If there is any doubt, return is_correct = false.
|
||||
words must be in the Standard language form, not slang, not broken, not phonetic guessing, not Nonsense & Partial.
|
||||
Inputs like [`ار`, `تس`, `کب`] Must be treated as incorrect, even if they could resemble:
|
||||
- A letter name in another language
|
||||
- A fragment of a real word
|
||||
- Other Languages.
|
||||
DO NOT guess meanings. DO NOT infer letters.
|
||||
|
||||
**Nearest Correct Word**
|
||||
|
||||
Only provide nearest_correct_word if:
|
||||
There is a very obvious and minimal edit-distance correction
|
||||
Otherwise return an empty string "".
|
||||
Plural & Zero-Width Non-Joiner (ZWNJ) Handling
|
||||
The following must be treated as correct Persian words:
|
||||
مهدیها
|
||||
مهدی\u200cها
|
||||
|
||||
Use:
|
||||
"persian" for Persian
|
||||
"arabic" for Arabic
|
||||
"unknown" if the word is incorrect or nonsense.
|
||||
|
||||
**Output Rules**
|
||||
|
||||
Output ONLY a valid Json object
|
||||
No explanations
|
||||
No extra text
|
||||
No markdown
|
||||
No assumptions
|
||||
|
||||
**Examples (for internal reasoning only)**
|
||||
|
||||
Input | is_correct | nearest_correct_word | lang
|
||||
مهدی ها | true | مهدی ها | persian
|
||||
مهدی\u200cها | true | مهدی\u200cها | persian
|
||||
ار | false | "" | unknown
|
||||
cta | false | cat | unknown
|
||||
سلامم | false | سلام | persian
|
||||
'''
|
||||
|
||||
|
||||
SYSTEM2 ='''Act like a deterministic, production-grade multilingual lexical validation engine with expert-level specialization in Persian (Farsi) linguistics and secondary competence in English and Arabic.
|
||||
|
||||
Your objective is to evaluate a single input string (a word or very short token) and determine, with maximum strictness and zero guesswork, whether it is a valid standalone word in any supported language. Your priority is linguistic correctness, dictionary validity, and grammatical acceptability over pattern matching or semantic inference.
|
||||
|
||||
Task:
|
||||
Given exactly one input string, analyze it and output a JSON object that strictly follows this schema and contains no extra fields:
|
||||
{
|
||||
"is_correct": boolean,
|
||||
"nearest_correct_word": string,
|
||||
"lang": string
|
||||
}
|
||||
|
||||
Follow these steps precisely:
|
||||
|
||||
Step 1: Normalize the input.
|
||||
Handle Unicode normalization, including Persian Zero-Width Non-Joiner (ZWNJ / half-space). Differences caused solely by Unicode normalization must not affect correctness.
|
||||
|
||||
Step 2: Language determination.
|
||||
Check whether the input is a fully valid word in:
|
||||
- Standard Persian (فارسی معیار)
|
||||
- English
|
||||
- Arabic
|
||||
If and only if the word is unquestionably valid in one language, proceed. If there is any uncertainty, ambiguity, slang usage, fragment possibility, or informal usage, treat it as invalid.
|
||||
|
||||
Step 3: Persian-specific validation (highest priority).
|
||||
A Persian word must:
|
||||
- Exist as a standard dictionary-valid word or proper name form
|
||||
- Be correctly spelled
|
||||
- Be grammatically acceptable as a standalone word
|
||||
- Not be slang, colloquial, phonetic, partial, or a morpheme fragment
|
||||
Random strings, partial stems, prefixes, or visually plausible fragments are always incorrect.
|
||||
|
||||
Step 4: Nonsense and partial token rejection.
|
||||
Inputs that are incomplete, meaningless, or could only become valid with additional letters must be marked incorrect, even if they resemble real words or letters.
|
||||
|
||||
Step 5: nearest_correct_word assignment.
|
||||
Only provide a nearest_correct_word if there is an obvious, minimal edit-distance correction to a well-known valid word. Otherwise, return an empty string "".
|
||||
If is_correct = true, nearest_correct_word must be the normalized correct form of the input itself.
|
||||
|
||||
Step 6: Language field.
|
||||
Use exactly:
|
||||
- "fa" for Persian
|
||||
- "en" for English
|
||||
- "ar" for Arabic
|
||||
- "unknown" if the input is incorrect or nonsense
|
||||
|
||||
Output rules (non-negotiable):
|
||||
- Output ONLY the JSON object
|
||||
- No explanations, comments, markdown, or extra text
|
||||
- No assumptions or creative inference
|
||||
- Absolute strictness: when in doubt, mark is_correct = false
|
||||
|
||||
Take a deep breath and work on this problem step-by-step.
|
||||
'''
|
||||
|
||||
class WordV2(BaseModel):
|
||||
is_correct : bool
|
||||
nearest_correct_word : str
|
||||
lang: str
|
||||
|
||||
if __name__ == '__main__':
|
||||
in_file = '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_list.json'
|
||||
in_file = load_orjson(in_file)
|
||||
in_file = in_file[:100]
|
||||
f_data = make_data(in_file)
|
||||
|
||||
save_orjson(
|
||||
data=f_data,
|
||||
path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/data100_test_v2.json'
|
||||
)
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.word_v2.ready_data
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
from aiDataParser import AsyncCore
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
import time
|
||||
|
||||
class WordV2(BaseModel):
|
||||
is_correct : bool
|
||||
nearest_correct_word : str
|
||||
lang: str
|
||||
|
||||
# /home2/MODELS/llama4/Llama-4-Scout-17B-16E-Instruct
|
||||
if __name__ == '__main__':
|
||||
start = time.time()
|
||||
ruuner1 = AsyncCore(
|
||||
model_name='gemma-3-27b',
|
||||
data_path= '/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/data_analyze.json',
|
||||
output_path='/home1/ava3/init_mahdi/project/aiDataParser/task/word_bank_proccess/word_v2/report_article/gemma3_27b',
|
||||
api_url="http://127.0.0.1:8004/v1/",# "http://172.16.29.102:8001/v1/",
|
||||
task_name='word-gemma-3-27b',
|
||||
output_schema=WordV2,
|
||||
reasoning_effort='medium',
|
||||
ai_code_version='gemma3_27b_medv1',
|
||||
request_timeout=30,
|
||||
save_number=100,
|
||||
semaphore_number=10,
|
||||
priority=1,
|
||||
)
|
||||
ruuner1.async_eval()
|
||||
end = time.time()
|
||||
|
||||
print(f'Time {end-start:.2f}')
|
||||
print(':D')
|
||||
|
||||
# python3 -m aiDataParser.task.word_bank_proccess.word_v2.run
|
||||
Reference in New Issue
Block a user