Arabic250 commited on
Commit
23520be
·
verified ·
1 Parent(s): 210e796

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import torch
4
+ import requests
5
+ from PIL import Image
6
+ from io import BytesIO
7
+ from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
8
+
9
+ model_id = 'Arabic250/gemma-4-E4B-it'
10
+ quantization_config = BitsAndBytesConfig(
11
+ load_in_4bit=True,
12
+ bnb_4bit_compute_dtype=torch.bfloat16,
13
+ bnb_4bit_quant_type='nf4',
14
+ bnb_4bit_use_double_quant=True
15
+ )
16
+
17
+ processor = AutoProcessor.from_pretrained(model_id)
18
+ model = AutoModelForImageTextToText.from_pretrained(
19
+ model_id,
20
+ quantization_config=quantization_config,
21
+ device_map='auto'
22
+ )
23
+
24
+ def predict_chat(message, history):
25
+ try:
26
+ parts = message.split(' ', 1)
27
+ has_url = parts[0].startswith('http')
28
+ if has_url:
29
+ image_url = parts[0]
30
+ user_prompt = parts[1] if len(parts) > 1 else 'صف هذه الصورة'
31
+ response = requests.get(image_url, stream=True)
32
+ image = Image.open(BytesIO(response.content)).convert('RGB')
33
+ else:
34
+ image = Image.new('RGB', (224, 224), color = (255, 255, 255))
35
+ user_prompt = message
36
+
37
+ messages = [{'role': 'user', 'content': [{'type': 'image'}, {'type': 'text', 'text': user_prompt}]}]
38
+ prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
39
+ inputs = processor(text=prompt, images=image, return_tensors='pt').to(model.device)
40
+
41
+ with torch.inference_mode():
42
+ output = model.generate(**inputs, max_new_tokens=512, do_sample=True, temperature=0.7)
43
+
44
+ return processor.decode(output[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip()
45
+ except Exception as e: return f'Error: {str(e)}'
46
+
47
+ chat_interface = gr.ChatInterface(fn=predict_chat, title='Gemma-4-E4B-it Arabic Space')
48
+ chat_interface.launch()