monir , majles update2
This commit is contained in:
@@ -2,6 +2,9 @@ import pickle
|
||||
import re
|
||||
import string
|
||||
import os
|
||||
import pickle, os, orjson, string, re, openpyxl
|
||||
from pathlib import Path
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
|
||||
class DataHelper():
|
||||
@@ -150,3 +153,115 @@ class DataHelper():
|
||||
|
||||
verb_tense_map = [verb_p2f_map, verb_f2p_map]
|
||||
return lexicon_stem, verb_stem, verb_tense_map, irregular_noun
|
||||
|
||||
@staticmethod
|
||||
def save_orjson(path, data):
|
||||
"""
|
||||
تابع برای ذخیره لیست و جیسون با سرعت بالا
|
||||
|
||||
:param path: آدرس خروجی با پسوند json
|
||||
:param data: داده خروجی برای ذخیره
|
||||
"""
|
||||
with open(path, "wb") as f:
|
||||
f.write(
|
||||
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def load_orjson(path: str | Path):
|
||||
"""
|
||||
تابع برای بارگزاری جیسون با نهایت سرعت
|
||||
path: آدرس کامل فایل ورودی
|
||||
"""
|
||||
path = Path(path)
|
||||
with path.open("rb") as f: # باید باینری باز بشه برای orjson
|
||||
return orjson.loads(f.read())
|
||||
|
||||
@staticmethod
|
||||
def html_to_clean_text(html: str) -> str:
|
||||
"""
|
||||
Parse HTML 2 PLAIN TEXT
|
||||
"""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
# تبدیل تگهای ساختاری به newline
|
||||
for tag in soup.find_all(['br', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
|
||||
tag.append("\n")
|
||||
|
||||
# حذف همهی استایلها و تگهای اضافی
|
||||
for tag in soup():
|
||||
if tag.name not in ['a']:
|
||||
tag.attrs = {} # remove style, class, dir, etc.
|
||||
|
||||
# استخراج متن خام
|
||||
text = soup.get_text("\n")
|
||||
|
||||
# حذف newline های اضافی
|
||||
text = re.sub(r'\n{2,}', '\n', text)
|
||||
|
||||
# حذف فاصلههای خاص HTML
|
||||
text = text.replace(u'\xa0', ' ').strip()
|
||||
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def json_to_excel(data, output_path="output.xlsx"):
|
||||
"""
|
||||
data: list of dict
|
||||
output_path: path to save excel file
|
||||
"""
|
||||
if not data:
|
||||
raise ValueError("JSON data is empty.")
|
||||
|
||||
# ساختن فایل اکسل
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Sheet1"
|
||||
|
||||
# ستونها
|
||||
headers = list(data[0].keys())
|
||||
ws.append(headers)
|
||||
|
||||
# ردیفها
|
||||
for item in data:
|
||||
row = [item.get(h, "") for h in headers]
|
||||
ws.append(row)
|
||||
|
||||
wb.save(output_path)
|
||||
return output_path
|
||||
|
||||
|
||||
@staticmethod
|
||||
def count_tokens(model_name, system_prompt, user_prompt):
|
||||
|
||||
"""
|
||||
شمارش دقیق توکنهای ورودی برای مدلهای مختلف
|
||||
"""
|
||||
text = f"<|system|>\n{system_prompt}\n<|user|>\n{user_prompt}"
|
||||
|
||||
# --- انتخاب tokenizer ---
|
||||
if "openai" in model_name.lower() or "gpt" in model_name.lower():
|
||||
import tiktoken
|
||||
# مدلهای مشابه GPT یا OSS از tiktoken استفاده میکنند
|
||||
enc = tiktoken.get_encoding("cl100k_base")
|
||||
tokens = enc.encode(text)
|
||||
return len(tokens)
|
||||
|
||||
elif "gemma" in model_name.lower():
|
||||
from transformers import AutoTokenizer
|
||||
# SentencePiece tokenizer (Gemma از HuggingFace)
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
tokens = tokenizer.encode(text)
|
||||
return len(tokens)
|
||||
|
||||
elif "magistral" in model_name.lower() or "mistral" in model_name.lower():
|
||||
from transformers import AutoTokenizer
|
||||
# Mistral / Magistral tokenizer (BPE)
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
||||
tokens = tokenizer.encode(text)
|
||||
return len(tokens)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Model {model_name} not recognized.")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user