yunusserhat commited on
Commit
dbef910
1 Parent(s): 952b253

Upload 2 files

Browse files
Files changed (2) hide show
  1. GPT4o_class.py +225 -0
  2. app.py +130 -0
GPT4o_class.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import base64
3
+ import requests
4
+ from tqdm import tqdm
5
+ from requests.exceptions import RequestException
6
+ from PIL import Image
7
+ from transformers import CLIPModel, CLIPProcessor
8
+ import torch
9
+ import faiss
10
+ import pickle
11
+ import numpy as np
12
+ import pandas as pd
13
+ from geopy.distance import geodesic
14
+ from transformers import AutoTokenizer, BitsAndBytesConfig
15
+ import torch
16
+ from PIL import Image
17
+ import requests
18
+ from io import BytesIO
19
+ import os
20
+
21
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
22
+
23
+
24
+ class GPT4o:
25
+ """
26
+ A class to interact with OPENAI API to generate captions for images.
27
+ """
28
+
29
+ def __init__(self, device="cpu") -> None:
30
+ """
31
+ Initializes the GPT4o class by setting up necessary models and data.
32
+ """
33
+
34
+ self.base64_image = None
35
+ self.img_emb = None
36
+
37
+ # Set the device to the first CUDA device
38
+ self.device = torch.device(device)
39
+
40
+ # Load the CLIP model and processor
41
+ self.model = CLIPModel.from_pretrained("geolocal/StreetCLIP").eval()
42
+ self.processor = CLIPProcessor.from_pretrained("geolocal/StreetCLIP")
43
+
44
+ # Move the model to the appropriate CUDA device
45
+ self.model.to(self.device)
46
+
47
+ # Load the embeddings and coordinates from the pickle file
48
+ with open('', 'rb') as f: # Enter the path to the pickle file
49
+ self.MP_16_Embeddings = pickle.load(f)
50
+ self.locations = [value['location'] for key, value in self.MP_16_Embeddings.items()]
51
+
52
+ # Load the Faiss index
53
+ index2 = faiss.read_index("") # Enter the path to the Faiss index file
54
+ self.gpu_index = index2
55
+
56
+ def read_image(self, image_path):
57
+ """
58
+ Reads an image from a file into a numpy array.
59
+ Args:
60
+ image_path (str): The path to the image file.
61
+ Returns:
62
+ np.ndarray: The image as a numpy array.
63
+ """
64
+ image = cv2.imread(image_path)
65
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
66
+ return image
67
+
68
+ def search_neighbors(self, faiss_index, k_nearest, k_farthest, query_embedding):
69
+ """
70
+ Searches for the k nearest and farthest neighbors of a query image in the Faiss index.
71
+ Args:
72
+ faiss_index (faiss.swigfaiss.Index): The Faiss index.
73
+ k_nearest (int): The number of nearest neighbors to search for.
74
+ k_farthest (int): The number of farthest neighbors to search for.
75
+ query_embedding (np.ndarray): The embeddings of the query image.
76
+ Returns:
77
+ tuple: The locations of the k nearest and k farthest neighbors.
78
+ """
79
+ # Perform the search using Faiss for the given embedding
80
+ _, I = faiss_index.search(query_embedding.reshape(1, -1), k_nearest)
81
+ self.neighbor_locations_array = [self.locations[idx] for idx in I[0]]
82
+ neighbor_locations = " ".join([str(i) for i in self.neighbor_locations_array])
83
+
84
+ # Perform the farthest search using Faiss for the given embedding
85
+ _, I = faiss_index.search(-query_embedding.reshape(1, -1), k_farthest)
86
+ self.farthest_locations_array = [self.locations[idx] for idx in I[0]]
87
+ farthest_locations = " ".join([str(i) for i in self.farthest_locations_array])
88
+
89
+ return neighbor_locations, farthest_locations
90
+
91
+ def encode_image(self, image: np.ndarray, format: str = 'jpeg') -> str:
92
+ """
93
+ Encodes an OpenCV image to a Base64 string.
94
+ Args:
95
+ image (np.ndarray): An image represented as a numpy array.
96
+ format (str, optional): The format for encoding the image. Defaults to 'jpeg'.
97
+ Returns:
98
+ str: A Base64 encoded string of the image.
99
+ Raises:
100
+ ValueError: If the image conversion fails.
101
+ """
102
+ try:
103
+ retval, buffer = cv2.imencode(f'.{format}', image)
104
+ if not retval:
105
+ raise ValueError("Failed to convert image")
106
+
107
+ base64_encoded = base64.b64encode(buffer).decode('utf-8')
108
+ mime_type = f"image/{format}"
109
+ return f"data:{mime_type};base64,{base64_encoded}"
110
+ except Exception as e:
111
+ raise ValueError(f"Error encoding image: {e}")
112
+
113
+ def set_image_app(self, file_uploader, imformat: str = 'jpeg', use_database_search: bool = False,
114
+ num_neighbors: int = 16, num_farthest: int = 16) -> None:
115
+ """
116
+ Sets the image for the class by encoding it to Base64.
117
+ Args:
118
+ file_uploader : A uploaded image (PIL Image from Gradio).
119
+ imformat (str, optional): The format for encoding the image. Defaults to 'jpeg'.
120
+ use_database_search (bool, optional): Whether to use a database search to get the neighbor image location as a reference. Defaults to False.
121
+ """
122
+
123
+ # Convert the PIL Image (Gradio upload) to a numpy array
124
+ img_array = np.array(file_uploader)
125
+
126
+ # Process the image using the CLIP processor
127
+ image = self.processor(images=img_array, return_tensors="pt")
128
+
129
+ # Move the image to the CUDA device and get its embeddings
130
+ image = image.to(self.device)
131
+ with torch.no_grad():
132
+ img_emb = self.model.get_image_features(**image)[0]
133
+
134
+ # Store the embeddings and the locations of the nearest neighbors
135
+ self.img_emb = img_emb.cpu().numpy()
136
+ if use_database_search:
137
+ self.neighbor_locations, self.farthest_locations = self.search_neighbors(self.gpu_index, num_neighbors,
138
+ num_farthest, self.img_emb)
139
+
140
+ # Encode the image to Base64
141
+ self.base64_image = self.encode_image(img_array, imformat)
142
+
143
+ def create_payload(self, question: str) -> dict:
144
+ """
145
+ Creates the payload for the API request to OpenAI.
146
+ Args:
147
+ question (str): The question to ask about the image.
148
+ Returns:
149
+ dict: The payload for the API request.
150
+ Raises:
151
+ ValueError: If the image is not set.
152
+ """
153
+ if not self.base64_image:
154
+ raise ValueError("Image not set")
155
+ return {
156
+ "model": "gpt-4o", # Can change to any other model
157
+ "messages": [
158
+ {
159
+ "role": "user",
160
+ "content": [
161
+ {
162
+ "type": "text",
163
+ "text": question
164
+ },
165
+ {
166
+ "type": "image_url",
167
+ "image_url": {
168
+ "url": self.base64_image
169
+ }
170
+ }
171
+ ]
172
+ }
173
+ ],
174
+ "max_tokens": 300,
175
+ }
176
+
177
+ def get_location(self, OPENAI_API_KEY, use_database_search: bool = False) -> str:
178
+ """
179
+ Generates a caption for the provided image using OPENAI API.
180
+ Args:
181
+ OPENAI_API_KEY (str): The API key for OPENAI API.
182
+ use_database_search (bool, optional): Whether to use a database search to get the neighbor image location as a reference. Defaults to False.
183
+ Returns:
184
+ str: The generated caption for the image.
185
+ """
186
+ try:
187
+ self.api_key = OPENAI_API_KEY
188
+ if not self.api_key:
189
+ raise ValueError("OPENAI API key not found")
190
+
191
+ # Create the question for the API
192
+ if use_database_search:
193
+ self.question = f'''Suppose you are an expert in geo-localization. Please analyze this image and give me a guess of the location.
194
+ Your answer must be to the coordinates level, don't include any other information in your output.
195
+ Ignore that you can't give an exact answer, give me some coordinate no matter how.
196
+ For your reference, these are locations of some similar images {self.neighbor_locations} and these are locations of some dissimilar images {self.farthest_locations} that should be far away.'''
197
+ else:
198
+ self.question = "Suppose you are an expert in geo-localization. Please analyze this image and give me a guess of the location. Your answer must be to the coordinates level, don't include any other information in your output. You can give me a guessed answer."
199
+
200
+ # Create the payload and the headers for the API request
201
+ payload = self.create_payload(self.question)
202
+ headers = {
203
+ "Content-Type": "application/json",
204
+ "Authorization": f"Bearer {self.api_key}"
205
+ }
206
+
207
+ # Send the API request and get the response
208
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
209
+ response.raise_for_status()
210
+ response_data = response.json()
211
+
212
+ # Log the full response for debugging
213
+ # print("Full API Response:", response_data)
214
+
215
+ # Return the generated caption
216
+ if 'choices' in response_data and len(response_data['choices']) > 0:
217
+ return response_data['choices'][0]['message']['content']
218
+ else:
219
+ raise ValueError("Unexpected response format from API")
220
+ except RequestException as e:
221
+ raise ValueError(f"Error in API request: {e}")
222
+ except KeyError as e:
223
+ raise ValueError(f"Key error in response: {e} - Response: {response_data}")
224
+ except ValueError as e:
225
+ raise ValueError(f"Value error: {e} - Response: {response_data}")
app.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import torch
4
+ import folium
5
+ from io import BytesIO
6
+ from GPT4o_class import GPT4o
7
+
8
+ # Initialize the GPT4v2Loc object
9
+ geo_locator = GPT4o(device="cuda" if torch.cuda.is_available() else "cpu")
10
+
11
+
12
+ # Function to handle the main processing logic
13
+ def process_image(uploaded_file, openai_api_key, num_nearest_neighbors, num_farthest_neighbors):
14
+ if not openai_api_key:
15
+ return "Please add your API key to continue.", None
16
+
17
+ if uploaded_file is None:
18
+ return "Please upload an image.", None
19
+
20
+ # Use the set_image_app method to process the uploaded image
21
+ geo_locator.set_image_app(
22
+ file_uploader=uploaded_file,
23
+ imformat='jpeg',
24
+ use_database_search=True, # Assuming you want to use the nearest/farthest neighbors
25
+ num_neighbors=num_nearest_neighbors,
26
+ num_farthest=num_farthest_neighbors
27
+ )
28
+
29
+ # Get the location from the OPENAI API
30
+ coordinates = geo_locator.get_location(
31
+ OPENAI_API_KEY=openai_api_key,
32
+ use_database_search=True # Assuming you want to use the nearest/farthest neighbors
33
+ )
34
+
35
+ lat_str, lon_str = coordinates.split(',')
36
+ lat_str = lat_str.strip("() ")
37
+ lon_str = lon_str.strip("() ")
38
+ latitude = float(lat_str)
39
+ longitude = float(lon_str)
40
+
41
+ # Generate the prediction map
42
+ prediction_map = folium.Map(location=[latitude, longitude], zoom_start=12)
43
+ folium.Marker([latitude, longitude], tooltip='Img2Loc Location',
44
+ popup=f'latitude: {latitude}, longitude: {longitude}',
45
+ icon=folium.Icon(color="red", icon="map-pin", prefix="fa")).add_to(prediction_map)
46
+ folium.TileLayer('cartodbpositron').add_to(prediction_map)
47
+
48
+ # Generate the nearest neighbor map
49
+ nearest_map = None
50
+ if geo_locator.neighbor_locations_array:
51
+ nearest_map = folium.Map(location=geo_locator.neighbor_locations_array[0], zoom_start=4)
52
+ folium.TileLayer('cartodbpositron').add_to(nearest_map)
53
+ for i in geo_locator.neighbor_locations_array:
54
+ folium.Marker(i, tooltip=f'({i[0]}, {i[1]})',
55
+ icon=folium.Icon(color="green", icon="compass", prefix="fa")).add_to(nearest_map)
56
+
57
+ # Generate the farthest neighbor map
58
+ farthest_map = None
59
+ if geo_locator.farthest_locations_array:
60
+ farthest_map = folium.Map(location=geo_locator.farthest_locations_array[0], zoom_start=3)
61
+ folium.TileLayer('cartodbpositron').add_to(farthest_map)
62
+ for i in geo_locator.farthest_locations_array:
63
+ folium.Marker(i, tooltip=f'({i[0]}, {i[1]})',
64
+ icon=folium.Icon(color="blue", icon="compass", prefix="fa")).add_to(farthest_map)
65
+
66
+ # Convert maps to HTML representations
67
+ prediction_map_html = map_to_html(prediction_map)
68
+ nearest_map_html = map_to_html(nearest_map) if nearest_map else ""
69
+ farthest_map_html = map_to_html(farthest_map) if farthest_map else ""
70
+
71
+ # Create a combined HTML output for Gradio
72
+ combined_html = f"""
73
+ <div style="text-align: center;">
74
+ <h3>Prediction Map</h3>
75
+ {prediction_map_html}
76
+ <div style="display: flex; justify-content: space-between; margin-top: 20px;">
77
+ <div style="flex: 1; margin-right: 10px;">
78
+ <h4>Nearest Neighbor Points Map</h4>
79
+ {nearest_map_html}
80
+ </div>
81
+ <div style="flex: 1; margin-left: 10px;">
82
+ <h4>Farthest Neighbor Points Map</h4>
83
+ {farthest_map_html}
84
+ </div>
85
+ </div>
86
+ </div>
87
+ """
88
+
89
+ # Return the coordinates (location information) and the combined HTML with maps
90
+ return coordinates, combined_html
91
+
92
+
93
+ def map_to_html(map_obj):
94
+ """
95
+ Convert a Folium map to an HTML representation.
96
+ """
97
+ return map_obj._repr_html_()
98
+
99
+
100
+ # Gradio Interface
101
+ with gr.Blocks() as vision_app:
102
+ with gr.Row():
103
+ with gr.Column():
104
+ uploaded_file = gr.Image(label="Upload an image")
105
+ openai_api_key = gr.Textbox(label="API Key", placeholder="xxxxxxxxx", type="password")
106
+
107
+ with gr.Accordion("Advanced Options", open=False):
108
+ num_nearest_neighbors = gr.Number(label="Number of nearest neighbors", value=16)
109
+ num_farthest_neighbors = gr.Number(label="Number of farthest neighbors", value=16)
110
+
111
+ submit = gr.Button("Submit")
112
+
113
+ with gr.Column():
114
+ status = gr.Textbox(label="Predicted Location")
115
+ maps_display = gr.HTML(label="Generated Maps") # Using HTML for correct map rendering
116
+
117
+ submit.click(
118
+ process_image,
119
+ inputs=[
120
+ uploaded_file,
121
+ openai_api_key,
122
+ num_nearest_neighbors,
123
+ num_farthest_neighbors
124
+ ],
125
+ outputs=[status, maps_display]
126
+ )
127
+
128
+ vision_app.launch()
129
+
130
+