Spaces:
Runtime error
Runtime error
File size: 8,719 Bytes
40f9cbe 65afb18 40f9cbe 65afb18 40f9cbe 65afb18 3efc3e4 18cf203 | 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 207 208 209 210 211 212 213 214 215 216 217 | import os
import re
import json
import base64
import traceback
import pandas as pd
import gradio as gr
import nest_asyncio
from PIL import Image
import io
# Google GenAI imports
import google.generativeai as genai
from google.genai import types
# MCP imports (for image enhancement)
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from mcp import StdioServerParameters
# --- Configure Colab / API Key ---
# Modify: Use os.environ for GOOGLE_API_KEY retrieval
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
if not GOOGLE_API_KEY:
raise ValueError("β GOOGLE_API_KEY not found in environment variables!")
genai.configure(api_key=GOOGLE_API_KEY)
# --- Apply nest_asyncio for MCP async calls ---
nest_asyncio.apply()
# --- MCP tool for image enhancement (background) ---
mcp_tool = McpToolset(
connection_params=StdioConnectionParams(
server_params=StdioServerParameters(
command="npx",
args=["-y", "@modelcontextprotocol/server-everything"],
tool_filter=["enhanceImage"]
),
timeout=30,
)
)
def mcp_enhance_image(path_or_url):
"""Enhance image in background and return base64 (not displayed)"""
with open(path_or_url, "rb") as f:
img_bytes = f.read()
img_b64 = base64.b64encode(img_bytes).decode()
try:
resp = mcp_tool.call_tool("enhanceImage", {"image": {"inline_data":{"mime_type":"image/jpeg","data": img_b64}}})
enhanced_b64 = resp.get("inline_data", {}).get("data", img_b64)
return enhanced_b64
except Exception as e:
print("MCP enhancement error:", e)
return img_b64
# --- Utilities ---
def img_to_part(path_or_url):
"""Prepare image for LLM"""
with open(path_or_url, "rb") as f:
img_bytes = f.read()
return {"inline_data":{"mime_type":"image/jpeg","data": base64.b64encode(img_bytes).decode()}}
def extract_json_from_text(text: str):
"""Robust JSON extraction from LLM output"""
try:
codeblock_match = re.search(r'```json\s*({.*?})\s*```', text, re.DOTALL | re.IGNORECASE)
candidate = codeblock_match.group(1) if codeblock_match else None
if not candidate:
start = text.find('{'); end = text.rfind('}')
if start != -1 and end != -1: candidate = text[start:end+1]
if not candidate: raise json.JSONDecodeError("No JSON found", text, 0)
candidate = re.sub(r',\s*}', '}', candidate)
candidate = re.sub(r',\s*]', ']', candidate)
return json.loads(candidate)
except Exception as e:
raise json.JSONDecodeError(f"Failed to parse JSON. {e}", text, 0)
# --- Generative Model ---
MODEL = genai.GenerativeModel(model_name="gemini-2.5-flash-lite")
# --- Vehicle Agent with Model Year Prediction ---
def vehicle_data_agent(image_path):
enhanced_b64 = mcp_enhance_image(image_path)
image_part = {"inline_data":{"mime_type":"image/jpeg","data": enhanced_b64}}
prompt = """
You are a vehicle documentation assistant.
Analyze the image and return JSON with fields:
type, make, model, model_year, color, license_plate, notes.
- Always fill model_year.
- If not visible, predict plausible model_year using other fields (make, model, type, color, body style).
- Output ONLY JSON.
"""
try:
resp = MODEL.generate_content([prompt, image_part])
text = "".join([p.text for p in resp.parts if hasattr(p,'text')]).strip()
vehicle_json = extract_json_from_text(text)
for k in ["type","make","model","model_year","color","license_plate","notes"]:
vehicle_json[k] = str(vehicle_json.get(k,"Unknown"))
my = str(vehicle_json.get("model_year","")).strip()
if not my or my.lower() in ["", "null", "none", "?"]:
secondary_prompt = f"""
You are an automobile expert. Predict the model_year based on the following features:
Make: {vehicle_json.get('make','')}
Model: {vehicle_json.get('model','')}
Type: {vehicle_json.get('type','')}
Color: {vehicle_json.get('color','')}
Notes: {vehicle_json.get('notes','')}
Return only JSON: {{ "model_year": "YYYY" }} or {{ "model_year": "YYYY-YYYY" }}
"""
resp2 = MODEL.generate_content([secondary_prompt])
text2 = "".join([p.text for p in resp2.parts if hasattr(p,'text')]).strip()
try:
predicted = extract_json_from_text(text2)
vehicle_json["model_year"] = str(predicted.get("model_year","Unknown"))
except:
vehicle_json["model_year"] = "Unknown"
return vehicle_json
except Exception as e:
return {"error": str(e), "traceback": traceback.format_exc()}
# --- Part Agent ---
def part_agent(part_name, image_path):
enhanced_b64 = mcp_enhance_image(image_path)
image_part = {"inline_data":{"mime_type":"image/jpeg","data": enhanced_b64}}
prompt = f"""
You are an expert automobile inspector.
Analyze {part_name}. Return numeric rating (0-10), advantages, disadvantages, condition.
Output as plain text starting with the numeric rating.
"""
try:
resp = MODEL.generate_content([prompt, image_part])
text = "".join([p.text for p in resp.parts if hasattr(p,'text')]).strip()
return text
except Exception as e:
return f"β Error: {e}"
# --- Supervisor Agent ---
def supervisor_agent(part_reports):
combined_text = "\n\n".join([f"{part}:\n{report}" for part, report in part_reports.items()])
prompt = f"""
Given multiple part reports:
{combined_text}
Return overall numeric rating (0-10), buying recommendation, and short summary as plain text.
"""
try:
resp = MODEL.generate_content([prompt])
text = "".join([p.text for p in resp.parts if hasattr(p,'text')]).strip()
return text
except Exception as e:
return f"β Error: {e}"
# --- Full Car Inspection ---
def full_car_inspection(full_vehicle=None, body=None, w1=None, w2=None, engine=None):
try:
parts = {
"body": body or "body.jpg",
"wheels": [w for w in [w1,w2] if w] or ["wheel1.jpg","wheel2.jpg"],
"engine": engine or "engine.jpg"
}
vehicle_info = vehicle_data_agent(full_vehicle or "full_vehicle.jpg")
rows, part_reports = [], {}
for part, imgs in parts.items():
imgs_list = imgs if isinstance(imgs,list) else [imgs]
for idx,img in enumerate(imgs_list,1):
report = part_agent(part,img)
part_reports[f"{part}_{idx}"] = report
rating_match = re.search(r"(\\d+(\.\\d+)?)", report)
rating = float(rating_match.group(1)) if rating_match else None
rows.append([part,f"{part}_{idx}",rating,report])
df_parts = pd.DataFrame(rows, columns=["Part","Image","Rating","Report"])
overall_summary = supervisor_agent(part_reports)
rating_match = re.search(r"overall numeric rating[:]*\\s*(\\d+)", overall_summary.lower())
emoji=""
if rating_match:
num_rating = int(rating_match.group(1))
if num_rating >= 8: emoji="π€©"
elif num_rating >= 6: emoji="π"
elif num_rating >= 4: emoji="π"
else: emoji="π"
overall_summary = f"{emoji} {overall_summary}"
return df_parts, pd.DataFrame([vehicle_info]), overall_summary
except Exception as e:
return pd.DataFrame(), pd.DataFrame(), f"Error: {e}"
# --- Gradio UI ---
with gr.Blocks() as demo:
# Blue background via HTML
gr.HTML("<style>body {background-color:#add8e6;}</style>")
gr.Markdown("## π Automobile Inspection Agent ")
# Upload images in a single row
with gr.Row():
full_vehicle_input = gr.Image(type="filepath", label="Full Vehicle")
body_input = gr.Image(type="filepath", label="Body Image")
wheel1_input = gr.Image(type="filepath", label="Wheel 1")
wheel2_input = gr.Image(type="filepath", label="Wheel 2")
engine_input = gr.Image(type="filepath", label="Engine")
run_btn = gr.Button("Run Inspection")
with gr.Row():
part_table = gr.DataFrame(label="Part Reports")
vehicle_table = gr.DataFrame(label="Vehicle Data")
summary_box = gr.Markdown(label="Overall Summary")
run_btn.click(
full_car_inspection,
inputs=[full_vehicle_input, body_input, wheel1_input, wheel2_input, engine_input],
outputs=[part_table, vehicle_table, summary_box]
)
demo.launch(share=True, debug=True) # Added a timestamp to force commit: 2024-07-29-14-30-00
# Last updated: 2025-12-04 20:26:41
# Last uploaded: 2025-12-04 20:58:23 |