| import gradio as gr |
| from PIL import Image |
| from ultralytics import YOLO |
| import requests |
| import json |
| import logging |
|
|
| logging.basicConfig(level=logging.INFO) |
|
|
| model = YOLO("500ml_Vs_1000ml_v1.pt") |
|
|
| def detect_objects(images): |
| results = model(images) |
| classes={0:"1000 ml", 1:"500 ml"} |
| names=[] |
| probss=[] |
| for result in results: |
| probs = result.probs.top1 |
| probss.append(probs) |
| |
| arr=[] |
| arr.append(classes[probs]) |
| names.append(arr) |
| return names |
|
|
| def create_solutions(image_urls, names): |
| solutions = [] |
|
|
| for image_url, class_name in zip(image_urls, names): |
| obj = {"url": image_url, "answer": [class_name] } |
| solutions.append(obj) |
| return solutions |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| def process_images(params): |
| try: |
| params = json.loads(params) |
| except json.JSONDecodeError as e: |
| logging.error(f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}") |
| return {"error": f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"} |
| |
| image_urls = params.get("urls", []) |
| |
| |
|
|
| if not image_urls: |
| logging.error("Missing required parameters: 'urls'") |
| return {"error": "Missing required parameters: 'urls'"} |
| |
| try: |
| images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls] |
| except Exception as e: |
| logging.error(f"Error loading images: {e}") |
| return {"error": f"Error loading images: {str(e)}"} |
| |
| names = detect_objects(images) |
| solutions = create_solutions(image_urls, names) |
|
|
| |
| |
|
|
| return json.dumps({"solutions": solutions}) |
|
|
|
|
| inputt = gr.Textbox(label="Parameters (JSON format) Eg. img_url:['','']") |
| outputs = gr.JSON() |
|
|
| application = gr.Interface(fn=process_images, inputs=inputt, outputs=outputs, title="500ML V 1000ML Classification with API Integration") |
| application.launch() |