Skip to content

Instantly share code, notes, and snippets.

@DraconicDragon
Last active May 11, 2025 16:55
Show Gist options
  • Select an option

  • Save DraconicDragon/a008bd12b2cf07a4b5a738e49cf3a8af to your computer and use it in GitHub Desktop.

Select an option

Save DraconicDragon/a008bd12b2cf07a4b5a738e49cf3a8af to your computer and use it in GitHub Desktop.
Script for running Florence2 based models
import requests
import torch
from PIL import Image
from transformers import AutoModelForCausalLM, AutoProcessor
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = r"microsoft/Florence-2-base" # can also use path/to/huggingface/hub/florence2-repo-name/snapshots/hash or something like that
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch_dtype, trust_remote_code=True).to(device)
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
prompt = "<CAPTION>"
# prompt = "<OCR>" # theres a lot more, look it up on HF
image_path = r"path/to/image.png"
image = Image.open(image_path).convert("RGB")
inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)
generated_ids = model.generate(
input_ids=inputs["input_ids"],
pixel_values=inputs["pixel_values"],
max_new_tokens=4096,
num_beams=3,
do_sample=False,
)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
# task = prompt here because too lazy to give it unique thingy
parsed_answer = processor.post_process_generation(generated_text, task=prompt, image_size=(image.width, image.height))
print(parsed_answer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment