File size: 8,838 Bytes
9d6fe53 b0c81df 9d6fe53 b0c81df 9d6fe53 b0c81df | 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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | # import requests
# import base64
# API_KEYS = [
# "AIzaSyCX8zI_mxdn6GOYRXogSsXsVr15b5iEUJM",
# "AIzaSyDvwkdHeCwoVuT3cIJLVIFlkw0-LblmdAg",
# "AIzaSyCOO9MTc8Ytx9-PUzpPMYA_MAygpAHKoh8",
# "AIzaSyD2cfooSLoqMfhJrvU339Mwo3utqzAkW9E",
# "AIzaSyCMxYblhF9PwWmqioQCDbDIxkthi1LqK4A",
# "AIzaSyDGNaIg9hk8jGG_QVkj55Vyev2SFlCU1CE"
# ]
# API_URL = "https://generativelanguage.googleapis.com/v1beta"
# WORKING_MODELS = [
# "models/gemini-1.5-flash-latest",
# "models/gemini-1.5-flash-001",
# "models/gemini-1.5-flash-001-tuning",
# "models/gemini-1.5-flash",
# "models/gemini-1.5-flash-002",
# "models/gemini-1.5-flash-8b",
# "models/gemini-1.5-flash-8b-001",
# "models/gemini-1.5-flash-8b-latest",
# "models/gemini-2.5-flash-preview-04-17",
# "models/gemini-2.5-flash-preview-05-20"
# ]
# def encode_image(image_path):
# with open(image_path, "rb") as image_file:
# image_bytes = image_file.read()
# return base64.b64encode(image_bytes).decode("utf-8")
# def query_model_with_image(model_name, image_path, api_key):
# url = f"{API_URL}/{model_name}:generateContent?alt=json&key={api_key}"
# encoded_image = encode_image(image_path)
# headers = {"Content-Type": "application/json"}
# data = {
# "contents": [{
# "parts": [
# {
# "text": (
# "Bạn hãy phân tích thông tin trong ảnh theo các tiêu chí sau. "
# "Nếu ảnh là chân dung một nhà triết học, hãy trả lời theo cấu trúc:\n"
# "- Tên:\n"
# "- Năm sinh - Năm mất:\n"
# "- Các tác phẩm kinh điển:\n"
# "- Những đóng góp đối với triết học:\n\n"
# "Nếu là một tác phẩm hội họa, hãy trả lời theo cấu trúc:\n"
# "- Tên tác phẩm:\n"
# "- Họa sĩ:\n"
# "- Các tác phẩm tiêu biểu khác:\n"
# "- Những đóng góp với triết học :\n\n"
# "Nếu là người thường hoặc ảnh không rõ, chỉ cần trả lời: 'Không rõ thông tin triết học'."
# )
# },
# {
# "inline_data": {
# "mime_type": "image/jpeg",
# "data": encoded_image
# }
# }
# ]
# }]
# }
# response = requests.post(url, headers=headers, json=data)
# return response
# def try_models_on_image(image_path):
# key_index = 0
# for model in WORKING_MODELS:
# success = False
# while key_index < len(API_KEYS):
# current_key = API_KEYS[key_index]
# print(f"\n🔍 Trying model: {model} with API key index {key_index}")
# try:
# res = query_model_with_image(model, image_path, current_key)
# if res.status_code == 200:
# output = res.json()
# text = output["candidates"][0]["content"]["parts"][0]["text"]
# print(f"✅ Success with {model} (API key index {key_index}):\n{text}")
# success = True
# break
# else:
# error_msg = res.json().get('error', {}).get('message', '')
# print(f"⚠️ Model failed ({res.status_code}): {error_msg}")
# if "quota" in error_msg.lower() or "exceeded" in error_msg.lower():
# print(f"⚠️ Quota exceeded for API key index {key_index}, switching to next key...")
# key_index += 1
# else:
# break
# except Exception as e:
# print(f"❌ Exception occurred with {model} (API key index {key_index}): {e}")
# key_index += 1
# if success:
# return
# print("\n🚫 All models failed or all API keys quota exceeded.")
# if __name__ == "__main__":
# image_path = "/home/nhattan05022003/coding/SEM_8/MLN_111/photo_restoration/output_img_folder/final_output/monalisa.png" # Đổi thành đường dẫn ảnh trên máy bạn
# try_models_on_image(image_path)
import requests
import base64
API_KEYS = [
"AIzaSyCX8zI_mxdn6GOYRXogSsXsVr15b5iEUJM",
"AIzaSyDvwkdHeCwoVuT3cIJLVIFlkw0-LblmdAg",
"AIzaSyCOO9MTc8Ytx9-PUzpPMYA_MAygpAHKoh8",
"AIzaSyD2cfooSLoqMfhJrvU339Mwo3utqzAkW9E",
"AIzaSyCMxYblhF9PwWmqioQCDbDIxkthi1Lq4A",
"AIzaSyDGNaIg9hk8jGG_QVkj55Vyev2SFlCU1CE"
]
API_URL = "https://generativelanguage.googleapis.com/v1beta"
WORKING_MODELS = [
"models/gemini-1.5-flash-latest",
"models/gemini-1.5-flash-001",
"models/gemini-1.5-flash-001-tuning",
"models/gemini-1.5-flash",
"models/gemini-1.5-flash-002",
"models/gemini-1.5-flash-8b",
"models/gemini-1.5-flash-8b-001",
"models/gemini-1.5-flash-8b-latest",
"models/gemini-2.5-flash-preview-04-17",
"models/gemini-2.5-flash-preview-05-20"
]
def encode_image(image_path):
with open(image_path, "rb") as image_file:
image_bytes = image_file.read()
return base64.b64encode(image_bytes).decode("utf-8")
def query_model_with_image(model_name, image_path, api_key):
url = f"{API_URL}/{model_name}:generateContent?alt=json&key={api_key}"
encoded_image = encode_image(image_path)
headers = {"Content-Type": "application/json"}
data = {
"contents": [{
"parts": [
{
"text": (
"Bạn hãy phân tích thông tin trong ảnh theo các tiêu chí sau. "
"Nếu ảnh là chân dung một nhà triết học, một người liên quan tới cách mạng, hãy trả lời theo cấu trúc:\n"
"- Tên:\n"
"- Năm sinh - Năm mất:\n"
"- Các tác phẩm kinh điển:\n"
"- Những đóng góp đối với triết học:\n\n"
"Nếu là một tác phẩm hội họa, hãy trả lời theo cấu trúc:\n"
"- Tên tác phẩm:\n"
"- Họa sĩ:\n"
"- Các tác phẩm tiêu biểu khác:\n"
"- Những đóng góp với triết học :\n\n"
"Nếu là người thường hoặc ảnh không rõ, chỉ cần trả lời: 'Không rõ thông tin triết học'."
)
},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": encoded_image
}
}
]
}]
}
response = requests.post(url, headers=headers, json=data)
return response
def try_models_on_image(image_path):
key_index = 0
for model in WORKING_MODELS:
success = False
while key_index < len(API_KEYS):
current_key = API_KEYS[key_index]
print(f"\n🔍 Trying model: {model} with API key index {key_index}")
try:
res = query_model_with_image(model, image_path, current_key)
if res.status_code == 200:
output = res.json()
text = output["candidates"][0]["content"]["parts"][0]["text"]
print(f"✅ Success with {model} (API key index {key_index}):\n{text}")
return text # Return the description
else:
error_msg = res.json().get('error', {}).get('message', '')
print(f"⚠️ Model failed ({res.status_code}): {error_msg}")
if "quota" in error_msg.lower() or "exceeded" in error_msg.lower():
print(f"⚠️ Quota exceeded for API key index {key_index}, switching to next key...")
key_index += 1
else:
break
except Exception as e:
print(f"❌ Exception occurred with {model} (API key index {key_index}): {e}")
key_index += 1
if success:
return ""
print("\n🚫 All models failed or all API keys quota exceeded.")
return "" # Return empty string if all attempts fail
if __name__ == "__main__":
image_path = "/home/nhattan05022003/coding/SEM_8/MLN_111/photo_restoration/output_img_folder/final_output/monalisa.png"
description = try_models_on_image(image_path)
print(f"Final description: {description}") |