Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,149 +1,178 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
|
|
|
| 4 |
import requests
|
| 5 |
from io import BytesIO
|
| 6 |
-
from PIL import Image
|
| 7 |
-
from transformers import AutoProcessor, VisionEncoderDecoderModel, AutoTokenizer
|
| 8 |
import gradio as gr
|
|
|
|
| 9 |
|
| 10 |
-
# -----------------------
|
| 11 |
-
# مدلهای انتخابی
|
| 12 |
-
# -----------------------
|
| 13 |
-
# مدل فارسی (قابل اجرا روی CPU 16GB)
|
| 14 |
-
MODEL_FARSI = "arxyzan/Qwen2-VL-2B-Instruct-Farsi"
|
| 15 |
-
# مدل انگلیسی (قابل اجرا روی CPU 16GB)
|
| 16 |
-
MODEL_ENGLISH = "microsoft/git-base-textcaps"
|
| 17 |
-
|
| 18 |
-
# انتخاب مدل پیشفرض
|
| 19 |
-
MODEL_NAME = MODEL_FARSI # تغییر بده اگر انگلیسی خواستی
|
| 20 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 21 |
-
|
| 22 |
-
# -----------------------
|
| 23 |
# مدیریت حافظه
|
| 24 |
-
|
| 25 |
-
def cleanup_memory():
|
| 26 |
-
try:
|
| 27 |
-
if torch.cuda.is_available():
|
| 28 |
-
torch.cuda.empty_cache()
|
| 29 |
-
except Exception:
|
| 30 |
-
pass
|
| 31 |
-
gc.collect()
|
| 32 |
-
|
| 33 |
-
cleanup_memory()
|
| 34 |
-
|
| 35 |
-
# -----------------------
|
| 36 |
-
# بارگذاری مدل
|
| 37 |
-
# -----------------------
|
| 38 |
-
try:
|
| 39 |
-
print(f"در حال بارگذاری مدل: {MODEL_NAME}")
|
| 40 |
-
processor = AutoProcessor.from_pretrained(MODEL_NAME)
|
| 41 |
-
model = VisionEncoderDecoderModel.from_pretrained(MODEL_NAME)
|
| 42 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 43 |
-
model.to(DEVICE)
|
| 44 |
-
print("✅ مدل با موفقیت بارگذاری شد!")
|
| 45 |
-
MODEL_LOADED = True
|
| 46 |
-
except Exception as e:
|
| 47 |
-
print(f"❌ خطا در بارگذاری مدل: {e}")
|
| 48 |
-
MODEL_LOADED = False
|
| 49 |
-
|
| 50 |
-
# -----------------------
|
| 51 |
-
# توابع کمکی
|
| 52 |
-
# -----------------------
|
| 53 |
-
def _is_garbage_text(s: str) -> bool:
|
| 54 |
-
if not s or len(s.strip()) <= 2:
|
| 55 |
-
return True
|
| 56 |
-
return False
|
| 57 |
-
|
| 58 |
-
def _strip_prompt_echo(generated_text: str, prompt: str) -> str:
|
| 59 |
-
if not generated_text:
|
| 60 |
-
return ""
|
| 61 |
-
if not prompt:
|
| 62 |
-
return generated_text.strip()
|
| 63 |
-
if generated_text.startswith(prompt):
|
| 64 |
-
return generated_text[len(prompt):].strip(" :.-\n\t")
|
| 65 |
-
return generated_text.strip()
|
| 66 |
-
|
| 67 |
-
# -----------------------
|
| 68 |
-
# تابع پردازش تصویر
|
| 69 |
-
# -----------------------
|
| 70 |
-
def process_image(image_url: str, prompt_text: str):
|
| 71 |
-
cleanup_memory()
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
return "❌ آدرس تصویر باید با http یا https شروع شود."
|
| 80 |
-
|
| 81 |
-
# دانلود تصویر
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
image = image.convert("RGB")
|
| 88 |
except Exception as e:
|
| 89 |
-
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
try:
|
| 93 |
-
inputs = processor(images=image, return_tensors="pt").to(DEVICE)
|
| 94 |
-
except Exception as e:
|
| 95 |
-
return f"❌ پردازش تصویر با processor ممکن نیست: {e}"
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
full_prompt = None
|
| 100 |
-
if prompt_text and prompt_text.strip():
|
| 101 |
-
full_prompt = prompt_text.strip()
|
| 102 |
-
try:
|
| 103 |
-
tok = tokenizer(full_prompt, return_tensors="pt")
|
| 104 |
-
decoder_input_ids = tok.input_ids.to(DEVICE)
|
| 105 |
-
except Exception as e:
|
| 106 |
-
return f"❌ خطا در توکنایز پرامپت: {e}"
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
try:
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
| 119 |
try:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
-
return f"❌
|
| 126 |
-
|
| 127 |
-
cleanup_memory()
|
| 128 |
-
return text
|
| 129 |
|
| 130 |
-
#
|
| 131 |
-
|
| 132 |
-
#
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
gr.Markdown("پرامپت را به فارسی یا انگلیسی وارد کنید تا خروجی تولید شود. اگر خالی باشد، مدل متن توصیفی ایجاد میکند.")
|
| 136 |
with gr.Row():
|
| 137 |
-
gr.Markdown(f"
|
|
|
|
|
|
|
|
|
|
| 138 |
with gr.Row():
|
| 139 |
-
with gr.Column(
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
if __name__ == "__main__":
|
| 149 |
-
demo.launch(
|
|
|
|
| 1 |
import os
|
| 2 |
+
from huggingface_hub import login, whoami
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
from PIL import Image
|
| 5 |
import requests
|
| 6 |
from io import BytesIO
|
|
|
|
|
|
|
| 7 |
import gradio as gr
|
| 8 |
+
import torch
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# مدیریت حافظه
|
| 11 |
+
torch.cuda.empty_cache() if torch.cuda.is_available() else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# خواندن توکن
|
| 14 |
+
HF_TOKEN = os.environ.get('bermuda')
|
| 15 |
|
| 16 |
+
# بررسی اتصال
|
| 17 |
+
connection_status = "🔒 حالت عمومی"
|
| 18 |
+
if HF_TOKEN:
|
|
|
|
|
|
|
|
|
|
| 19 |
try:
|
| 20 |
+
login(token=HF_TOKEN)
|
| 21 |
+
user_info = whoami()
|
| 22 |
+
connection_status = f"✅ متصل به: {user_info['name']}"
|
| 23 |
+
print(connection_status)
|
|
|
|
| 24 |
except Exception as e:
|
| 25 |
+
connection_status = f"⚠️ خطا در اتصال: {e}"
|
| 26 |
+
print(connection_status)
|
| 27 |
|
| 28 |
+
print("📥 در حال بارگیری بهترین مدل چندزبانه برای CPU...")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
# بهترین انتخاب برای CPU + چندزبانگی
|
| 31 |
+
BEST_MODEL = "microsoft/git-large" # 🏆 برنده نهایی
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
try:
|
| 34 |
+
print(f"🔍 بارگیری: {BEST_MODEL}")
|
| 35 |
+
|
| 36 |
+
pipe = pipeline(
|
| 37 |
+
"image-to-text",
|
| 38 |
+
model=BEST_MODEL,
|
| 39 |
+
device=-1, # CPU
|
| 40 |
+
torch_dtype=torch.float32
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
print("✅ مدل با موفقیت بارگیری شد!")
|
| 44 |
+
model_loaded = True
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"❌ خطا در بارگیری: {e}")
|
| 48 |
+
# جایگزین
|
| 49 |
try:
|
| 50 |
+
BEST_MODEL = "Salesforce/blip2-opt-2.7b"
|
| 51 |
+
pipe = pipeline("image-to-text", model=BEST_MODEL, device=-1)
|
| 52 |
+
model_loaded = True
|
| 53 |
+
print(f"✅ مدل جایگزین {BEST_MODEL} بارگیری شد!")
|
| 54 |
+
except:
|
| 55 |
+
model_loaded = False
|
| 56 |
+
|
| 57 |
+
def process_multilingual(image_url, instruction_text, language):
|
| 58 |
+
"""پردازش چندزبانه"""
|
| 59 |
+
if not model_loaded:
|
| 60 |
+
return "❌ مدل بارگیری نشده است"
|
| 61 |
+
|
| 62 |
try:
|
| 63 |
+
if not image_url.startswith('http'):
|
| 64 |
+
return "❌ آدرس تصویر نامعتبر"
|
| 65 |
+
|
| 66 |
+
# دانلود تصویر
|
| 67 |
+
response = requests.get(image_url, timeout=30)
|
| 68 |
+
image = Image.open(BytesIO(response.content))
|
| 69 |
+
|
| 70 |
+
if image.mode != 'RGB':
|
| 71 |
+
image = image.convert('RGB')
|
| 72 |
+
|
| 73 |
+
print(f"🌍 پردازش به زبان: {language}")
|
| 74 |
+
|
| 75 |
+
# ساخت دستور با توجه به زبان
|
| 76 |
+
if language == "فارسی":
|
| 77 |
+
prompt = instruction_text if instruction_text.strip() else "این تصویر را توصیف کن"
|
| 78 |
+
elif language == "English":
|
| 79 |
+
prompt = instruction_text if instruction_text.strip() else "Describe this image"
|
| 80 |
+
elif language == "العربية":
|
| 81 |
+
prompt = instruction_text if instruction_text.strip() else "صف هذه الصورة"
|
| 82 |
+
elif language == "中文":
|
| 83 |
+
prompt = instruction_text if instruction_text.strip() else "描述这张图片"
|
| 84 |
+
elif language == "Español":
|
| 85 |
+
prompt = instruction_text if instruction_text.strip() else "Describe esta imagen"
|
| 86 |
+
else:
|
| 87 |
+
prompt = instruction_text if instruction_text.strip() else "Describe this image"
|
| 88 |
+
|
| 89 |
+
# پردازش
|
| 90 |
+
result = pipe(image, prompt)
|
| 91 |
+
generated_text = result[0]['generated_text']
|
| 92 |
+
|
| 93 |
+
return f"**زبان: {language}**\n\n{generated_text}"
|
| 94 |
+
|
| 95 |
except Exception as e:
|
| 96 |
+
return f"❌ خطا: {str(e)}"
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
# رابط چندزبانه
|
| 99 |
+
with gr.Blocks(title="پردازشگر چندزبانه تصویر", theme=gr.themes.Soft()) as demo:
|
| 100 |
+
gr.Markdown("# 🌍 پردازشگر چندزبانه تصاویر")
|
| 101 |
+
gr.Markdown("**پشتیبانی از فارسی، انگلیسی، عربی، چینی و اسپانیایی**")
|
| 102 |
+
|
|
|
|
| 103 |
with gr.Row():
|
| 104 |
+
gr.Markdown(f"**وضعیت:** {connection_status}")
|
| 105 |
+
gr.Markdown(f"**مدل:** {BEST_MODEL}")
|
| 106 |
+
gr.Markdown("**⚡ بهینه برای CPU**")
|
| 107 |
+
|
| 108 |
with gr.Row():
|
| 109 |
+
with gr.Column():
|
| 110 |
+
image_url = gr.Textbox(
|
| 111 |
+
label="آدرس تصویر",
|
| 112 |
+
value="https://images.unsplash.com/photo-1541963463532-d68292c34b19?w=400",
|
| 113 |
+
lines=2
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
language = gr.Dropdown(
|
| 117 |
+
label="زبان خروجی",
|
| 118 |
+
choices=["فارسی", "English", "العربية", "中文", "Español"],
|
| 119 |
+
value="فارسی"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
instruction_text = gr.Textbox(
|
| 123 |
+
label="دستور (اختیاری)",
|
| 124 |
+
placeholder="متن دستور را به زبان انتخاب شده وارد کنی��...",
|
| 125 |
+
value="",
|
| 126 |
+
lines=2
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
submit_btn = gr.Button("🚀 پردازش چندزبانه", variant="primary")
|
| 130 |
+
|
| 131 |
+
with gr.Column():
|
| 132 |
+
output_text = gr.Markdown(
|
| 133 |
+
label="نتیجه پردازش"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# اطلاعات مدل
|
| 137 |
+
with gr.Accordion("🏆 اطلاعات مدل", open=True):
|
| 138 |
+
gr.Markdown("""
|
| 139 |
+
**microsoft/git-large - بهترین برای CPU:**
|
| 140 |
+
- ✅ سبک و سریع (0.4B پارامتر)
|
| 141 |
+
- 🌍 پشتیبانی از ۱۰۰+ زبان
|
| 142 |
+
- ⚡ پردازش ۱۰-۳۰ ثانیهای
|
| 143 |
+
- 🎯 کیفیت عالی در همه زبانها
|
| 144 |
+
""")
|
| 145 |
+
|
| 146 |
+
# مثالهای چندزبانه
|
| 147 |
+
with gr.Accordion("🌐 مثالهای چندزبانه", open=False):
|
| 148 |
+
examples = gr.Examples(
|
| 149 |
+
examples=[
|
| 150 |
+
[
|
| 151 |
+
"https://images.unsplash.com/photo-1541963463532-d68292c34b19?w=400",
|
| 152 |
+
"این تصویر را با جزئیات توصیف کن",
|
| 153 |
+
"فارسی"
|
| 154 |
+
],
|
| 155 |
+
[
|
| 156 |
+
"https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Orange_tabby_cat_sitting_on_fallen_leaves-Hisashi-01A.jpg/400px-Orange_tabby_cat_sitting_on_fallen_leaves-Hisashi-01A.jpg",
|
| 157 |
+
"Describe this cat and its environment",
|
| 158 |
+
"English"
|
| 159 |
+
],
|
| 160 |
+
[
|
| 161 |
+
"https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400",
|
| 162 |
+
"صف هذا المنظر الطبيعي",
|
| 163 |
+
"العربية"
|
| 164 |
+
],
|
| 165 |
+
],
|
| 166 |
+
inputs=[image_url, instruction_text, language],
|
| 167 |
+
outputs=[output_text]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
submit_btn.click(
|
| 171 |
+
fn=process_multilingual,
|
| 172 |
+
inputs=[image_url, instruction_text, language],
|
| 173 |
+
outputs=[output_text],
|
| 174 |
+
show_progress="full"
|
| 175 |
+
)
|
| 176 |
|
| 177 |
if __name__ == "__main__":
|
| 178 |
+
demo.launch()
|