File size: 5,081 Bytes
a783ac1 | 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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import base64
import requests
import json
import mimetypes
def get_server_ip():
ip = os.getenv("server_ip")
if ip:
return ip
try:
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
if os.path.exists(env_path):
with open(env_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
parts = line.split('=', 1)
key = parts[0].strip()
val = parts[1].strip().strip('\'"')
if key == "server_ip":
return val
except Exception:
pass
return "10.112.5.79"
def check_image(image_path_or_url="/home/ivan/eagle/cat.jpg", prompt_text="照片裡面有什麼?請遵照以下格式做輸出 {'danger':0, 'reason':text_resopn},如果是危險生物的話,danger 輸出為1,反之輸出為0,並在reason說明原因"):
server_ip = get_server_ip()
url = f"http://{server_ip}:4000/v1/chat/completions"
headers = {
"Content-Type": "application/json"
}
resolved_image_url = image_path_or_url
is_local = False
# Check if the path exists locally on this machine
if os.path.exists(image_path_or_url):
is_local = True
try:
# Guess MIME type (e.g. image/jpeg, image/png)
mime_type, _ = mimetypes.guess_type(image_path_or_url)
if not mime_type:
mime_type = "image/jpeg"
# Read local file and encode to base64
with open(image_path_or_url, "rb") as image_file:
base64_data = base64.b64encode(image_file.read()).decode("utf-8")
resolved_image_url = f"data:{mime_type};base64,{base64_data}"
except Exception as e:
print(f"Warning: Failed to read local image file '{image_path_or_url}': {e}")
print("Sending path as-is instead.")
payload = {
"model": "openbmb/MiniCPM-V-4.6",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": resolved_image_url
}
},
{
"type": "text",
"text": prompt_text
}
]
}
]
}
print(f"Sending request to {url}...")
if is_local:
print(f"Image Source: {image_path_or_url} (local file, encoded in base64)")
else:
print(f"Image Source: {image_path_or_url} (remote/server path)")
print(f"Prompt: {prompt_text}\n")
try:
response = requests.post(url, headers=headers, json=payload, timeout=60)
response.raise_for_status() # Check for HTTP errors
# Parse JSON response
result = response.json()
# Print raw response metadata
print("=== Raw Response ===")
print(json.dumps(result, indent=2, ensure_ascii=False))
print("====================\n")
# Extract assistant message content
choices = result.get("choices", [])
if choices:
content = choices[0].get("message", {}).get("content", "")
print("=== Extracted Content ===")
print(content)
print("=========================")
return content
else:
print("Error: No choices returned in the response.")
return None
except requests.exceptions.Timeout:
print("Error: Request timed out. Make sure the API server is responsive.")
return None
except requests.exceptions.ConnectionError:
print(f"Error: Connection failed. Please check if the API server at {server_ip}:4000 is running.")
return None
except requests.exceptions.HTTPError as http_err:
print(f"HTTP Error occurred: {http_err}")
try:
print("Response body:")
print(response.text)
except Exception:
pass
return None
except Exception as err:
print(f"An unexpected error occurred: {err}")
return None
if __name__ == "__main__":
# If users provide arguments, they can customize the image and prompt.
# E.g., python3 image_check.py "picture.jpeg" "照片裡有什麼?"
img_arg = sys.argv[1] if len(sys.argv) > 1 else "/home/ivan/eagle/cat.jpg"
prompt_arg = sys.argv[2] if len(sys.argv) > 2 else "照片裡面有什麼?請遵照以下格式做輸出 {'danger':0, 'reason':text_resopn},如果是危險生物的話,danger 輸出為1,反之輸出為0,並在reason說明原因"
check_image(image_path_or_url=img_arg, prompt_text=prompt_arg)
|