Update app.py
Browse files
app.py
CHANGED
|
@@ -1,40 +1,41 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
|
| 3 |
-
import torch
|
| 4 |
-
from PIL import Image
|
| 5 |
import requests
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 12 |
|
| 13 |
-
# Use GPU if available
|
| 14 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 15 |
-
model.to(device)
|
| 16 |
-
|
| 17 |
-
# Caption generation function
|
| 18 |
def generate_alt_text(image):
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
iface = gr.Interface(
|
| 32 |
fn=generate_alt_text,
|
| 33 |
-
inputs=gr.Image(type="pil"
|
| 34 |
-
outputs=gr.Textbox(label="
|
| 35 |
-
title="
|
| 36 |
-
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
# Launch app
|
| 40 |
-
iface.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 3 |
import requests
|
| 4 |
+
import base64
|
| 5 |
+
import io
|
| 6 |
|
| 7 |
+
HF_MODEL = "llava-hf/llava-v1.6-mistral-7b-hf"
|
| 8 |
+
HF_TOKEN = os.getenv("HF_API_TOKEN")
|
| 9 |
+
API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
|
| 10 |
+
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
|
|
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
def generate_alt_text(image):
|
| 13 |
+
buffered = io.BytesIO()
|
| 14 |
+
image.save(buffered, format="JPEG")
|
| 15 |
+
b64 = base64.b64encode(buffered.getvalue()).decode()
|
| 16 |
+
|
| 17 |
+
payload = {
|
| 18 |
+
"inputs": [
|
| 19 |
+
{
|
| 20 |
+
"role": "user",
|
| 21 |
+
"content": [
|
| 22 |
+
{"type": "image", "image": b64},
|
| 23 |
+
{"type": "text", "text": "Describe this image in detail"}
|
| 24 |
+
],
|
| 25 |
+
}
|
| 26 |
+
],
|
| 27 |
+
"options": {"wait_for_model": True},
|
| 28 |
+
}
|
| 29 |
|
| 30 |
+
resp = requests.post(API_URL, headers=HEADERS, json=payload)
|
| 31 |
+
if resp.status_code != 200:
|
| 32 |
+
return f"Error: {resp.status_code}"
|
| 33 |
+
output = resp.json()
|
| 34 |
+
return output[0]["generated_text"].strip()
|
| 35 |
|
| 36 |
+
gr.Interface(
|
|
|
|
| 37 |
fn=generate_alt_text,
|
| 38 |
+
inputs=gr.Image(type="pil"),
|
| 39 |
+
outputs=gr.Textbox(label="Alt Text from LLaVA"),
|
| 40 |
+
title="Inference‑based Rich Alt Text"
|
| 41 |
+
).launch()
|
|
|
|
|
|
|
|
|
|
|
|