-
Notifications
You must be signed in to change notification settings - Fork 1
/
caption_generator.py
50 lines (40 loc) · 1.29 KB
/
caption_generator.py
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
import os
from transformers import AutoProcessor, AutoModelForVision2Seq
from PIL import Image
import torch
import requests
# # Load processor and model
# processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
# model = AutoModelForVision2Seq.from_pretrained("Salesforce/blip-image-captioning-large")
#
#
# def caption_generator(image):
# """
# Generates a caption for the given image.
#
# Parameters:
# image (PIL.Image.Image): The image for which to generate a caption.
#
# Returns:
# str: The generated caption.
# """
#
# # Preprocess the image
# inputs = processor(images=image, return_tensors="pt")
#
# # Generate captions (inference)
# with torch.no_grad():
# outputs = model.generate(**inputs)
#
# # Decode the output
# caption = processor.decode(outputs[0], skip_special_tokens=True)
#
# return caption
API_URL = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
headers = {"Authorization": f"Bearer {os.environ.get('HF_TOKEN')}"}
def caption_generator(filename):
with open(filename, "rb") as f:
data = f.read()
response = requests.post(API_URL, headers=headers, data=data)
return response.json()
# output = query("/content/pexels-brakou-1723637.jpg")