PhilHolst commited on
Commit
f268596
·
1 Parent(s): ec9a31a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+
4
+ os.system("pip install -U gradio")
5
+ os.system("pip install detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu102/torch1.9/index.html")
6
+ os.system("git clone https://github.com/facebookresearch/Detic.git --recurse-submodules")
7
+
8
+ # Importing necessary libraries
9
+ import numpy as np
10
+ import cv2
11
+ from PIL import Image
12
+ from detectron2.utils.visualizer import Visualizer
13
+ from detectron2.data import MetadataCatalog
14
+ from detectron2.engine import DefaultPredictor
15
+ from detectron2.config import get_cfg
16
+
17
+ # Configuring model and predictor
18
+ cfg = get_cfg()
19
+ cfg.merge_from_file("Detic/configs/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.yaml")
20
+ cfg.MODEL.WEIGHTS = "https://dl.fbaipublicfiles.com/detic/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
21
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
22
+ predictor = DefaultPredictor(cfg)
23
+
24
+ # Caption generator
25
+ from langchain.llms import OpenAIChat
26
+ session_token = os.environ.get("SessionToken")
27
+
28
+ def generate_caption(object_list_str, api_key, temperature):
29
+ query = f"You are an intelligent image captioner. I will hand you the objects and their position, and you should give me a detailed description for the photo. In this photo we have the following objects\n{object_list_str}"
30
+ llm = OpenAIChat(
31
+ model_name="gpt-3.5-turbo", openai_api_key=api_key, temperature=temperature
32
+ )
33
+
34
+ try:
35
+ caption = llm(query)
36
+ caption = caption.strip()
37
+ except:
38
+ caption = "Sorry, something went wrong!"
39
+
40
+ return caption
41
+
42
+ # Model Inference
43
+ def caption_image(img):
44
+ im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
45
+ outputs = predictor(im)["instances"]
46
+
47
+ metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0])
48
+ v = Visualizer(im[:, :, ::-1], metadata=metadata)
49
+ out = v.draw_instance_predictions(outputs.to("cpu"))
50
+
51
+ detected_objects = []
52
+ object_list_str = []
53
+
54
+ for i, prediction in enumerate(outputs):
55
+ x0, y0, x1, y1 = prediction.pred_boxes.tensor[0].cpu().numpy()
56
+ width = x1 - x0
57
+ height = y1 - y0
58
+ predicted_label = metadata.thing_classes[prediction.pred_classes[0]]
59
+ detected_objects.append({
60
+ "prediction": predicted_label,
61
+ "x": int(x0),
62
+ "y": int(y0),
63
+ "w": int(width),
64
+ "h": int(height)
65
+ })
66
+ object_list_str.append(f"{predicted_label} - X:({int(x0)} Y: {int(y0)} Width {int(width)} Height: {int(height)})")
67
+
68
+ # GPT3 to generate caption
69
+ api_key = session_token
70
+ if api_key is not None:
71
+ gpt_response = generate_caption(object_list_str, api_key, temperature=0.7)
72
+ else:
73
+ gpt_response = "Please paste your OpenAI key to use"
74
+
75
+ return gpt_response
76
+
77
+ # Interface
78
+ image_input = gr.inputs.Image(shape=(896, 896))
79
+ caption_output = gr.outputs.Textbox()
80
+
81
+ gr.Interface(fn=caption_image, inputs=image_input, outputs=caption_output, title="Intelligent Image Captioning", description="Generate captions for an image with object detection.").launch()