Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,96 +1,111 @@
|
|
1 |
-
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import gc # برای آزاد کردن حافظه
|
5 |
-
import psutil # برای مانیتور کردن حافظه
|
6 |
|
7 |
class MultiModelSystem:
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
self.models = {}
|
|
|
10 |
|
11 |
-
def
|
12 |
-
"""
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
def unload_model(self, task):
|
23 |
-
"""
|
|
|
|
|
|
|
24 |
if task in self.models:
|
|
|
25 |
del self.models[task]
|
26 |
-
gc.collect()
|
27 |
-
|
28 |
-
@staticmethod
|
29 |
-
def load_openai_model():
|
30 |
-
"""مدل ریاضی OpenAI."""
|
31 |
-
return "OpenAI (Math)"
|
32 |
-
|
33 |
-
@staticmethod
|
34 |
-
def get_task_type(task):
|
35 |
-
task_map = {
|
36 |
-
"translation": "translation",
|
37 |
-
"qa": "question-answering",
|
38 |
-
"persian_nlp": "text-classification",
|
39 |
-
"custom_ai": "text-generation",
|
40 |
-
"math": "text-generation",
|
41 |
-
}
|
42 |
-
return task_map.get(task, "text-generation")
|
43 |
|
44 |
def process_task(self, task, model_id, **kwargs):
|
45 |
-
"""
|
46 |
-
|
47 |
-
|
|
|
|
|
|
|
|
|
48 |
model = self.models[task]
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
else:
|
54 |
-
|
55 |
|
56 |
-
def process_math_task(self, text):
|
57 |
-
"""مدیریت وظایف ریاضی OpenAI."""
|
58 |
-
try:
|
59 |
-
response = openai.ChatCompletion.create(
|
60 |
-
model="gpt-4",
|
61 |
-
messages=[{"role": "user", "content": text}]
|
62 |
-
)
|
63 |
-
return response['choices'][0]['message']['content'].strip()
|
64 |
-
except Exception as e:
|
65 |
-
print(f"Error processing math task: {e}")
|
66 |
-
return None
|
67 |
-
|
68 |
-
# مانیتورینگ حافظه
|
69 |
-
def check_memory_usage():
|
70 |
-
mem = psutil.virtual_memory()
|
71 |
-
print(f"Memory usage: {mem.percent}% ({mem.used / (1024 ** 3):.2f} GB used)")
|
72 |
-
|
73 |
-
# نمونه استفاده
|
74 |
if __name__ == "__main__":
|
|
|
75 |
MODEL_CONFIG = {
|
76 |
"translation": "PontifexMaximus/opus-mt-iir-en-finetuned-fa-to-en",
|
77 |
"qa": "HooshvareLab/bert-fa-base-uncased",
|
78 |
-
"math": "OpenAI",
|
79 |
-
"persian_nlp": "HooshvareLab/bert-fa-zwnj-base",
|
80 |
-
"custom_ai": "universitytehran/PersianMind-v1.0",
|
81 |
}
|
82 |
|
83 |
-
|
84 |
-
|
85 |
tasks = [
|
86 |
-
{"task": "translation", "model_id": MODEL_CONFIG["translation"], "kwargs": {"text": "سلام دنیا!"
|
87 |
-
{"task": "qa", "model_id": MODEL_CONFIG["qa"], "kwargs": {"question": "پایتخت ایران
|
88 |
-
{"task": "math", "model_id": MODEL_CONFIG["math"], "kwargs": {"text": "What is the integral of x^2?"}},
|
89 |
]
|
90 |
|
|
|
|
|
|
|
|
|
91 |
for task_info in tasks:
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
1 |
+
import gc
|
2 |
+
import psutil
|
3 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
|
|
|
|
4 |
|
5 |
class MultiModelSystem:
|
6 |
+
"""
|
7 |
+
سیستم چندمدلی برای مدیریت وظایف NLP با بهینهسازی مصرف حافظه.
|
8 |
+
"""
|
9 |
+
|
10 |
+
def __init__(self, memory_limit_gb=15):
|
11 |
+
"""
|
12 |
+
مقداردهی اولیه سیستم و تنظیم محدودیت حافظه.
|
13 |
+
:param memory_limit_gb: حداکثر میزان استفاده از حافظه.
|
14 |
+
"""
|
15 |
self.models = {}
|
16 |
+
self.memory_limit_gb = memory_limit_gb
|
17 |
|
18 |
+
def check_memory_usage(self):
|
19 |
+
"""
|
20 |
+
بررسی میزان استفاده از حافظه.
|
21 |
+
"""
|
22 |
+
mem = psutil.virtual_memory()
|
23 |
+
used_gb = mem.used / (1024 ** 3)
|
24 |
+
print(f"Memory usage: {mem.percent}% ({used_gb:.2f} GB used)")
|
25 |
+
if used_gb > self.memory_limit_gb:
|
26 |
+
raise MemoryError(f"Memory limit exceeded: {used_gb:.2f} GB used (limit: {self.memory_limit_gb} GB)")
|
27 |
+
|
28 |
+
def load_model(self, task, model_id):
|
29 |
+
"""
|
30 |
+
بارگذاری مدل بر اساس وظیفه.
|
31 |
+
:param task: نوع وظیفه (مثلاً ترجمه).
|
32 |
+
:param model_id: شناسه مدل.
|
33 |
+
"""
|
34 |
+
if task not in self.models:
|
35 |
+
self.check_memory_usage() # بررسی حافظه پیش از بارگذاری
|
36 |
+
print(f"Loading model for task '{task}' with ID '{model_id}'...")
|
37 |
+
if task == "translation":
|
38 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(
|
39 |
+
model_id,
|
40 |
+
torch_dtype="auto", # بهینهسازی حافظه با FP16
|
41 |
+
low_cpu_mem_usage=True
|
42 |
+
)
|
43 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
44 |
+
self.models[task] = pipeline("translation", model=model, tokenizer=tokenizer)
|
45 |
+
elif task == "qa":
|
46 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
47 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
48 |
+
self.models[task] = pipeline("question-answering", model=model, tokenizer=tokenizer)
|
49 |
+
else:
|
50 |
+
self.models[task] = pipeline(task, model=model_id)
|
51 |
|
52 |
def unload_model(self, task):
|
53 |
+
"""
|
54 |
+
آزادسازی مدل برای مدیریت حافظه.
|
55 |
+
:param task: نوع وظیفه.
|
56 |
+
"""
|
57 |
if task in self.models:
|
58 |
+
print(f"Unloading model for task '{task}'...")
|
59 |
del self.models[task]
|
60 |
+
gc.collect()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
def process_task(self, task, model_id, **kwargs):
|
63 |
+
"""
|
64 |
+
پردازش وظیفه با استفاده از مدل مناسب.
|
65 |
+
:param task: نوع وظیفه.
|
66 |
+
:param model_id: شناسه مدل.
|
67 |
+
:return: نتیجه پردازش.
|
68 |
+
"""
|
69 |
+
self.load_model(task, model_id)
|
70 |
model = self.models[task]
|
71 |
|
72 |
+
if task == "translation":
|
73 |
+
text = kwargs.get("text", "")
|
74 |
+
if not text:
|
75 |
+
raise ValueError("No input text provided for translation task.")
|
76 |
+
return model(text)
|
77 |
+
elif task == "qa":
|
78 |
+
question = kwargs.get("question", "")
|
79 |
+
context = kwargs.get("context", "")
|
80 |
+
if not question or not context:
|
81 |
+
raise ValueError("Both 'question' and 'context' must be provided for QA task.")
|
82 |
+
return model(question=question, context=context)
|
83 |
else:
|
84 |
+
raise ValueError(f"Unsupported task: {task}")
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
if __name__ == "__main__":
|
87 |
+
# تنظیمات مدلها
|
88 |
MODEL_CONFIG = {
|
89 |
"translation": "PontifexMaximus/opus-mt-iir-en-finetuned-fa-to-en",
|
90 |
"qa": "HooshvareLab/bert-fa-base-uncased",
|
|
|
|
|
|
|
91 |
}
|
92 |
|
93 |
+
# تعریف وظایف
|
|
|
94 |
tasks = [
|
95 |
+
{"task": "translation", "model_id": MODEL_CONFIG["translation"], "kwargs": {"text": "سلام دنیا!"}},
|
96 |
+
{"task": "qa", "model_id": MODEL_CONFIG["qa"], "kwargs": {"question": "پایتخت ایران کجاست؟", "context": "ایران کشوری در خاورمیانه است و پایتخت آن تهران است."}}
|
|
|
97 |
]
|
98 |
|
99 |
+
# نمونهسازی سیستم
|
100 |
+
system = MultiModelSystem(memory_limit_gb=15)
|
101 |
+
|
102 |
+
# پردازش وظایف
|
103 |
for task_info in tasks:
|
104 |
+
try:
|
105 |
+
system.check_memory_usage()
|
106 |
+
result = system.process_task(task_info["task"], task_info["model_id"], **task_info["kwargs"])
|
107 |
+
print(f"Result for task '{task_info['task']}':", result)
|
108 |
+
except Exception as e:
|
109 |
+
print(f"Error during task '{task_info['task']}':", str(e))
|
110 |
+
finally:
|
111 |
+
system.unload_model(task_info["task"]) # تخلیه مدل پس از اتمام
|