Spaces:
Running
Running
File size: 2,443 Bytes
1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 7a9da94 c6a8dd3 1a3f574 7a9da94 c6a8dd3 1a3f574 7a9da94 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 7a9da94 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 c6a8dd3 1a3f574 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | import gradio as gr
from transformers import (
BlipProcessor,
BlipForConditionalGeneration,
BlipForQuestionAnswering
)
print("Loading models...")
caption_processor = BlipProcessor.from_pretrained(
"Salesforce/blip-image-captioning-base"
)
caption_model = BlipForConditionalGeneration.from_pretrained(
"Salesforce/blip-image-captioning-base"
)
vqa_processor = BlipProcessor.from_pretrained(
"Salesforce/blip-vqa-base"
)
vqa_model = BlipForQuestionAnswering.from_pretrained(
"Salesforce/blip-vqa-base"
)
print("Models Loaded!")
def analyze_image(image, question):
if image is None:
return "", ""
caption_inputs = caption_processor(
image,
return_tensors="pt"
)
caption_ids = caption_model.generate(
**caption_inputs,
max_new_tokens=30
)
caption = caption_processor.decode(
caption_ids[0],
skip_special_tokens=True
)
answer = ""
if question and question.strip():
vqa_inputs = vqa_processor(
image,
question,
return_tensors="pt"
)
answer_ids = vqa_model.generate(
**vqa_inputs,
max_new_tokens=10
)
answer = vqa_processor.decode(
answer_ids[0],
skip_special_tokens=True
)
return caption, answer
with gr.Blocks(
title="Visual AI Assistant"
) as demo:
gr.Markdown(
"""
# Visual AI Assistant
This application uses BLIP models for:
- Image Captioning
- Visual Question Answering (VQA)
Upload an image and optionally ask a question about it.
"""
)
image_input = gr.Image(
type="pil",
label="Upload Image"
)
question_input = gr.Textbox(
label="Ask a Question",
placeholder="What is happening in this image?"
)
with gr.Row():
analyze_btn = gr.Button(
"Analyze Image"
)
clear_btn = gr.ClearButton(
[
image_input,
question_input
]
)
caption_output = gr.Textbox(
label="Generated Caption"
)
answer_output = gr.Textbox(
label="Answer"
)
analyze_btn.click(
fn=analyze_image,
inputs=[
image_input,
question_input
],
outputs=[
caption_output,
answer_output
]
)
demo.launch() |