Spaces:
Paused
Paused
Commit Β·
e581bf6
1
Parent(s): 074874b
Sync from GitHub
Browse filesFiles changed (14)
- README.md+150-57
- app.py+626-268
- hf_space/README.md+148-61
- hf_space/hf_space/README.md+185-12
- hf_space/hf_space/hf_space/hf_space/hf_space/.huggingface.yamlAdded+7
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.github/workflows/docker-build-push.ymlAdded+26
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.github/workflows/hf-space-sync.ymlAdded+36
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.gitignoreAdded+5
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/DockerfileAdded+13
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/LICENSEAdded+21
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/app.pyAdded+384
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.gitattributesAdded+35
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/README.mdAdded+12
- hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/requirements.txtAdded+8
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253541 unmodified line565758596061626364656667686970717273747576777879808182838485868788891 unmodified line9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361375 unmodified lines1431441451461471481491501511521531541551563 unmodified lines160161162163164165166167168169170171172173174175176177178179# π Object Detection with Transformer ModelsThis project provides an object detection system using state-of-the-art transformer models, such as **DETR (DEtection TRansformer)** and **YOLOS (You Only Look One-level Series)**. The system can detect objects from uploaded images or image URLs, and it supports different models for detection and segmentation tasks. It includes a Gradio-based web interface and a FastAPI-based API for programmatic access.You can try the demo online on Hugging Face: [Demo Link](https://huggingface.co/spaces/NeerajCodz/ObjectDetection).## Models SupportedThe following models are supported, as defined in the application:- **DETR (DEtection TRansformer)**:- `facebook/detr-resnet-50`: DETR with ResNet-50 backbone for object detection. Fast and accurate for general use.- `facebook/detr-resnet-101`: DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50.- `facebook/detr-resnet-50-panoptic`(currently has bugs): DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes.- `facebook/detr-resnet-101-panoptic`(currently has bugs): DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes.- **YOLOS (You Only Look One-level Series)**:- `hustvl/yolos-tiny`: YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments.- `hustvl/yolos-base`: YOLOS Base model. Balances speed and accuracy for object detection.## Features- **Image Upload**: Upload images from your device for object detection via the Gradio interface.- **URL Input**: Input an image URL for detection through the Gradio interface or API.- **Model Selection**: Choose between DETR and YOLOS models for detection or panoptic segmentation.- **Object Detection**: Detects objects and highlights them with bounding boxes and confidence scores.- **Panoptic Segmentation**: Some models (e.g., DETR panoptic variants) support detailed scene segmentation with colored masks.- **Image Properties**: Displays image metadata such as format, size, aspect ratio, file size, and color statistics.- **API Access**: Use the FastAPI endpoint `/detect` to programmatically process images and retrieve detection results.## How to Use### 1. **Normal Git Clone Method**Follow these steps to set up the application locally:#### Prerequisites- Python 3.8 or higher- Install dependencies using `pip`#### Clone the Repository```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```#### Install DependenciesInstall the required dependencies from `requirements.txt`:```bashpip install -r requirements.txt1 unmodified line#### Run the ApplicationStart the FastAPI server using uvicorn:```bashuvicorn objectdetection:app --reload```Alternatively, launch the Gradio interface by running the main script:```bashpython app.py```#### Access the Application- For FastAPI: Open your browser and navigate to `http://localhost:8000` to use the API or view the Swagger UI.- For Gradio: The Gradio interface URL will be displayed in the console (typically `http://127.0.0.1:7860`).### 2. **Running with Docker**If you prefer to use Docker to set up and run the application, follow these steps:#### Prerequisites- Docker installed on your machine. If you donβt have Docker, download and install it from [here](https://www.docker.com/get-started).#### Download the docker ImageFirst, Pull the docker Image:```bashdocker pull neerajcodz/objectdetection:latest1 unmodified line#### Run the Docker ContainerOnce the image is built, run the application using this command:```bashdocker run -d -p 8080:80 neerajcodz/objectdetection:latest```This will start the application on port 8080.Open your browser and go to `http://localhost:8080` to access the interface.### 3. **Demo**You can try the demo directly online through Hugging Face's Spaces:[Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection)## Using the API (Instable)You can interact with the application via the FastAPI `/detect` endpoint to send images and get detection results.**Endpoint**: `/detect`**POST**: `/detect`**Parameters**:- `file`: (optional) Image file (must be of type `image/*`).- `image_url`: (optional) URL of the image.- `model_name`: (optional) Choose from `facebook/detr-resnet-50`, `hustvl/yolos-tiny`, etc.**Example Request Body**:```json{"image_url": "https://example.com/image.jpg","model_name": "facebook/detr-resnet-50"}```**Response**:The response includes a base64-encoded image with detections, detected objects, confidence scores, and unique objects with their scores.```json{5 unmodified lines}```## Development SetupIf you'd like to contribute or modify the application:1. Clone the repository:```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```3 unmodified linespip install -r requirements.txt```3. Run the FastAPI server or Gradio interface:```bashuvicorn objectdetection:app --reload```or```bashpython app.py```4. Open your browser and navigate to `http://localhost:8000` (FastAPI) or the Gradio URL (typically `http://127.0.0.1:7860`).## ContributingContributions are welcome! Feel free to open issues or submit pull requests for bug fixes or new features on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455561 unmodified line585960616263646566676869707172737475767778798081828384858687888990911 unmodified line939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062075 unmodified lines2132142152162172182192202212222232242252262272282292302312323 unmodified lines236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272# π Object Detection with Transformer ModelsThis project provides a robust object detection system leveraging state-of-the-art transformer models, including **DETR (DEtection TRansformer)** and **YOLOS (You Only Look One-level Series)**. The system supports object detection and panoptic segmentation from uploaded images or image URLs. It features a user-friendly **Gradio** web interface for interactive use and a **FastAPI** endpoint for programmatic access.Try the online demo on Hugging Face Spaces: [Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection).## Models SupportedThe application supports the following models, each tailored for specific detection or segmentation tasks:- **DETR (DEtection TRansformer)**:- `facebook/detr-resnet-50`: Fast and accurate object detection with a ResNet-50 backbone.- `facebook/detr-resnet-101`: Higher accuracy object detection with a ResNet-101 backbone, slower than ResNet-50.- `facebook/detr-resnet-50-panoptic`: Panoptic segmentation with ResNet-50 (note: may have stability issues).- `facebook/detr-resnet-101-panoptic`: Panoptic segmentation with ResNet-101 (note: may have stability issues).- **YOLOS (You Only Look One-level Series)**:- `hustvl/yolos-tiny`: Lightweight and fast, ideal for resource-constrained environments.- `hustvl/yolos-base`: Balances speed and accuracy for object detection.## Features- **Image Upload**: Upload images via the Gradio interface for object detection.- **URL Input**: Provide image URLs for detection through the Gradio interface or API.- **Model Selection**: Choose between DETR and YOLOS models for detection or panoptic segmentation.- **Object Detection**: Highlights detected objects with bounding boxes and confidence scores.- **Panoptic Segmentation**: Supports scene segmentation with colored masks (DETR panoptic models).- **Image Properties**: Displays metadata like format, size, aspect ratio, file size, and color statistics.- **API Access**: Programmatically process images via the FastAPI `/detect` endpoint.- **Flexible Deployment**: Run locally, in Docker, or in cloud environments like Google Colab.## How to Use### 1. **Local Setup (Git Clone)**Follow these steps to set up the application locally:#### Prerequisites- Python 3.8 or higher- `pip` for installing dependencies- Git for cloning the repository#### Clone the Repository```bashgit clone https://github.com/NeerajCodz/ObjectDetectioncd ObjectDetection```#### Install DependenciesInstall required packages from `requirements.txt`:```bashpip install -r requirements.txt1 unmodified line#### Run the ApplicationLaunch the Gradio interface:```bashpython app.py```To enable the FastAPI server:```bashpython app.py --enable-fastapi```#### Access the Application- **Gradio**: Open the URL displayed in the console (typically `http://127.0.0.1:7860`).- **FastAPI**: Navigate to `http://localhost:8000` for the API or Swagger UI (if enabled).### 2. **Running with Docker**Use Docker for a containerized setup.#### Prerequisites- Docker installed on your machine. Download from [Docker's official site](https://www.docker.com/get-started).#### Pull the Docker ImagePull the pre-built image from Docker Hub:```bashdocker pull neerajcodz/objectdetection:latest1 unmodified line#### Run the Docker ContainerRun the application on port 8080:```bashdocker run -d -p 8080:80 neerajcodz/objectdetection:latest```Access the interface at `http://localhost:8080`.#### Build and Run the Docker ImageTo build the Docker image locally:1. Ensure you have a `Dockerfile` in the repository root (example provided in the repository).2. Build the image:```bashdocker build -t objectdetection:local .```3. Run the container:```bashdocker run -d -p 8080:80 objectdetection:local```Access the interface at `http://localhost:8080`.### 3. **Demo**Try the demo on Hugging Face Spaces:[Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection)## Command-Line ArgumentsThe `app.py` script supports the following command-line arguments:- `--gradio-port <port>`: Specify the port for the Gradio UI (default: 7860).- Example: `python app.py --gradio-port 7870`- `--enable-fastapi`: Enable the FastAPI server (disabled by default).- Example: `python app.py --enable-fastapi`- `--fastapi-port <port>`: Specify the port for the FastAPI server (default: 8000).- Example: `python app.py --enable-fastapi --fastapi-port 8001`You can combine arguments:```bashpython app.py --gradio-port 7870 --enable-fastapi --fastapi-port 8001```Alternatively, set the `GRADIO_SERVER_PORT` environment variable:```bashexport GRADIO_SERVER_PORT=7870python app.py```## Using the API**Note**: The FastAPI API is currently unstable and may require additional configuration for production use.The `/detect` endpoint allows programmatic image processing.### Running the FastAPI ServerEnable FastAPI when launching the script:```bashpython app.py --enable-fastapi```Or run FastAPI separately with Uvicorn:```bashuvicorn objectdetection:app --host 0.0.0.0 --port 8000```Access the Swagger UI at `http://localhost:8000/docs` for interactive testing.### Endpoint Details- **Endpoint**: `POST /detect`- **Parameters**:- `file`: (optional) Image file (must be `image/*` type).- `image_url`: (optional) URL of the image.- `model_name`: (optional) Model name (e.g., `facebook/detr-resnet-50`, `hustvl/yolos-tiny`).- **Content-Type**: `multipart/form-data` for file uploads, `application/json` for URL inputs.### Example Requests#### Using `curl` with an Image URL```bashcurl -X POST "http://localhost:8000/detect" \-H "Content-Type: application/json" \-d '{"image_url": "https://example.com/image.jpg", "model_name": "facebook/detr-resnet-50"}'```#### Using `curl` with an Image File```bashcurl -X POST "http://localhost:8000/detect" \-F "file=@/path/to/image.jpg" \-F "model_name=facebook/detr-resnet-50"```### Response FormatThe response includes a base64-encoded image with detections and detection details:```json{5 unmodified lines}```### Notes- Ensure only one of `file` or `image_url` is provided.- The API may experience instability with panoptic models; use object detection models for reliability.- Test the API using the Swagger UI for easier debugging.## Development SetupTo contribute or modify the application:1. Clone the repository:```bashgit clone https://github.com/NeerajCodz/ObjectDetectioncd ObjectDetection```3 unmodified linespip install -r requirements.txt```3. Run the application:```bashpython app.py```Or run FastAPI:```bashuvicorn objectdetection:app --host 0.0.0.0 --port 8000```4. Access at `http://localhost:7860` (Gradio) or `http://localhost:8000` (FastAPI).## ContributingContributions are welcome! To contribute:1. Fork the repository.2. Create a feature or bugfix branch (`git checkout -b feature/your-feature`).3. Commit changes (`git commit -m "Add your feature"`).4. Push to the branch (`git push origin feature/your-feature`).5. Open a pull request on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).Please include tests and documentation for new features. Report issues via GitHub Issues.## Troubleshooting- **Port Conflicts**: If port 7860 is in use, specify a different port with `--gradio-port` or set `GRADIO_SERVER_PORT`.- **Colab Issues**: Use the `--gradio-port` argument or environment variable to avoid port conflicts in Google Colab.- **Panoptic Model Bugs**: Avoid `detr-resnet-*-panoptic` models until stability issues are resolved.- **API Instability**: Test with smaller images and object detection models first.For further assistance, open an issue on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778793 unmodified lines83848586878817 unmodified lines1061071081091101111122 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711725 unmodified lines178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384import gradio as grimport torchfrom transformers import DetrImageProcessor, DetrForObjectDetectionfrom transformers import YolosImageProcessor, YolosForObjectDetectionfrom transformers import DetrForSegmentationfrom PIL import Image, ImageDraw, ImageStatimport requestsfrom io import BytesIOimport base64from collections import Counterimport loggingfrom fastapi import FastAPI, File, UploadFile, HTTPException, Formfrom fastapi.responses import JSONResponseimport uvicornimport pandas as pdimport tracebackimport os# Set up logginglogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)# ConstantsCONFIDENCE_THRESHOLD = 0.5VALID_MODELS = ["facebook/detr-resnet-50","facebook/detr-resnet-101","facebook/detr-resnet-50-panoptic","facebook/detr-resnet-101-panoptic","hustvl/yolos-tiny","hustvl/yolos-base"]MODEL_DESCRIPTIONS = {"facebook/detr-resnet-50": "DETR with ResNet-50 backbone for object detection. Fast and accurate for general use.","facebook/detr-resnet-101": "DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50.","facebook/detr-resnet-50-panoptic": "DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes.","facebook/detr-resnet-101-panoptic": "DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes.","hustvl/yolos-tiny": "YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments.","hustvl/yolos-base": "YOLOS Base model. Balances speed and accuracy for object detection."}# Lazy model loadingmodels = {}processors = {}def process(image, model_name):"""Process an image and return detected image, objects, confidences, unique objects, unique confidences, and properties."""try:if model_name not in VALID_MODELS:raise ValueError(f"Invalid model: {model_name}. Choose from: {VALID_MODELS}")# Load model and processorif model_name not in models:logger.info(f"Loading model: {model_name}")if "yolos" in model_name:models[model_name] = YolosForObjectDetection.from_pretrained(model_name)processors[model_name] = YolosImageProcessor.from_pretrained(model_name)elif "panoptic" in model_name:models[model_name] = DetrForSegmentation.from_pretrained(model_name)processors[model_name] = DetrImageProcessor.from_pretrained(model_name)else:models[model_name] = DetrForObjectDetection.from_pretrained(model_name)processors[model_name] = DetrImageProcessor.from_pretrained(model_name)model, processor = models[model_name], processors[model_name]inputs = processor(images=image, return_tensors="pt")with torch.no_grad():outputs = model(**inputs)target_sizes = torch.tensor([image.size[::-1]])draw = ImageDraw.Draw(image)object_names = []confidence_scores = []object_counter = Counter()if "panoptic" in model_name:processed_sizes = torch.tensor([[inputs["pixel_values"].shape[2], inputs["pixel_values"].shape[3]]])results = processor.post_process_panoptic(outputs, target_sizes=target_sizes, processed_sizes=processed_sizes)[0]3 unmodified lineslabel_name = model.config.id2label.get(label, "Unknown")score = segment.get("score", 1.0)if "masks" in results and segment["id"] < len(results["masks"]):mask = results["masks"][segment["id"]].cpu().numpy()if mask.shape[0] > 0 and mask.shape[1] > 0:17 unmodified linesx, y, x2, y2 = box.tolist()draw.rectangle([x, y, x2, y2], outline="#32CD32", width=2)label_name = model.config.id2label.get(label.item(), "Unknown")# Place text at top-right corner, outside the box, with smaller sizetext = f"{label_name}: {score:.2f}"text_bbox = draw.textbbox((0, 0), text)text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]2 unmodified linesconfidence_scores.append(float(score))object_counter[label_name] = float(score)unique_objects = list(object_counter.keys())unique_confidences = [object_counter[obj] for obj in unique_objects]# Image propertiesfile_size = "Unknown"if hasattr(image, "fp") and image.fp is not None:buffered = BytesIO()image.save(buffered, format="PNG")file_size = f"{len(buffered.getvalue()) / 1024:.2f} KB"# Color statisticstry:stat = ImageStat.Stat(image)color_stats = {"mean": [f"{m:.2f}" for m in stat.mean],"stddev": [f"{s:.2f}" for s in stat.stddev]}except Exception as e:logger.error(f"Error calculating color statistics: {str(e)}")color_stats = {"mean": "Error", "stddev": "Error"}properties = {"Format": image.format if hasattr(image, "format") and image.format else "Unknown","Size": f"{image.width}x{image.height}","Width": f"{image.width} px","Height": f"{image.height} px","Mode": image.mode,"Aspect Ratio": f"{round(image.width / image.height, 2) if image.height != 0 else 'Undefined'}","File Size": file_size,"Mean (R,G,B)": ", ".join(color_stats["mean"]) if isinstance(color_stats["mean"], list) else color_stats["mean"],"StdDev (R,G,B)": ", ".join(color_stats["stddev"]) if isinstance(color_stats["stddev"], list) else color_stats["stddev"]}return image, object_names, confidence_scores, unique_objects, unique_confidences, propertiesexcept Exception as e:logger.error(f"Error in process: {str(e)}\n{traceback.format_exc()}")raise# FastAPI Setupapp = FastAPI(title="Object Detection API")@app.post("/detect")async def detect_objects_endpoint(file: UploadFile = File(None),image_url: str = Form(None),model_name: str = Form(VALID_MODELS[0])):"""FastAPI endpoint to detect objects in an image from file or URL."""try:if (file is None and not image_url) or (file is not None and image_url):raise HTTPException(status_code=400, detail="Provide either an image file or an image URL, but not both.")if file:if not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="File must be an image")5 unmodified linesimage = Image.open(BytesIO(response.content)).convert("RGB")if model_name not in VALID_MODELS:raise HTTPException(status_code=400, detail=f"Invalid model. Choose from: {VALID_MODELS}")detected_image, detected_objects, detected_confidences, unique_objects, unique_confidences, _ = process(image, model_name)buffered = BytesIO()detected_image.save(buffered, format="PNG")img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")img_url = f"data:image/png;base64,{img_base64}"return JSONResponse(content={"image_url": img_url,"detected_objects": detected_objects,"confidence_scores": detected_confidences,"unique_objects": unique_objects,"unique_confidence_scores": unique_confidences})except Exception as e:logger.error(f"Error in FastAPI endpoint: {str(e)}\n{traceback.format_exc()}")raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")# Gradio UIdef create_gradio_ui():with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="gray")) as demo:gr.Markdown("""# π Object Detection AppUpload an image or provide a URL to detect objects using state-of-the-art transformer models (DETR, YOLOS).""")with gr.Tabs():with gr.Tab("π· Image Upload"):with gr.Row():with gr.Column(scale=1):gr.Markdown("### Input")model_choice = gr.Dropdown(choices=VALID_MODELS,value=VALID_MODELS[0],label="π Select Model",info="Choose a model for object detection or panoptic segmentation.")model_info = gr.Markdown(f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}",visible=True)image_input = gr.Image(type="pil", label="π· Upload Image")image_url_input = gr.Textbox(label="π Image URL",placeholder="https://example.com/image.jpg")with gr.Row():submit_btn = gr.Button("β¨ Detect", variant="primary")clear_btn = gr.Button("ποΈ Clear", variant="secondary")model_choice.change(fn=lambda model_name: f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}",inputs=model_choice,outputs=model_info)with gr.Column(scale=2):gr.Markdown("### Results")error_output = gr.Textbox(label="β οΈ Errors",visible=False,lines=3,max_lines=5)output_image = gr.Image(type="pil",label="π― Detected Image",interactive=False)with gr.Row():objects_output = gr.DataFrame(label="π Detected Objects",interactive=False,value=None)unique_objects_output = gr.DataFrame(label="π Unique Objects",interactive=False,value=None)properties_output = gr.DataFrame(label="π Image Properties",interactive=False,value=None)def process_for_gradio(image, url, model_name):try:if image is None and not url:return None, None, None, None, "Please provide an image or URL"if image and url:return None, None, None, None, "Please provide either an image or URL, not both"if url:response = requests.get(url, timeout=10)response.raise_for_status()image = Image.open(BytesIO(response.content)).convert("RGB")detected_image, objects, scores, unique_objects, unique_scores, properties = process(image, model_name)objects_df = pd.DataFrame({"Object": objects,"Confidence Score": [f"{score:.2f}" for score in scores]}) if objects else pd.DataFrame(columns=["Object", "Confidence Score"])unique_objects_df = pd.DataFrame({"Unique Object": unique_objects,"Confidence Score": [f"{score:.2f}" for score in unique_scores]}) if unique_objects else pd.DataFrame(columns=["Unique Object", "Confidence Score"])properties_df = pd.DataFrame([properties]) if properties else pd.DataFrame(columns=properties.keys())return detected_image, objects_df, unique_objects_df, properties_df, ""except Exception as e:error_msg = f"Error processing image: {str(e)}"logger.error(f"{error_msg}\n{traceback.format_exc()}")return None, None, None, None, error_msgsubmit_btn.click(fn=process_for_gradio,inputs=[image_input, image_url_input, model_choice],outputs=[output_image, objects_output, unique_objects_output, properties_output, error_output])clear_btn.click(fn=lambda: [None, "", None, None, None, None],inputs=None,outputs=[image_input, image_url_input, output_image, objects_output, unique_objects_output, properties_output, error_output])with gr.Tab("π URL Input"):gr.Markdown("### Process Image from URL")image_url_input = gr.Textbox(label="π Image URL",placeholder="https://example.com/image.jpg")url_model_choice = gr.Dropdown(choices=VALID_MODELS,value=VALID_MODELS[0],label="π Select Model")url_model_info = gr.Markdown(f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}",visible=True)url_submit_btn = gr.Button("π Process URL", variant="primary")url_output = gr.JSON(label="API Response")url_model_choice.change(fn=lambda model_name: f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}",inputs=url_model_choice,outputs=url_model_info)def process_url_for_gradio(url, model_name):try:response = requests.get(url, timeout=10)response.raise_for_status()image = Image.open(BytesIO(response.content)).convert("RGB")detected_image, objects, scores, unique_objects, unique_scores, _ = process(image, model_name)buffered = BytesIO()detected_image.save(buffered, format="PNG")img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")return {"image_url": f"data:image/png;base64,{img_base64}","detected_objects": objects,"confidence_scores": scores,"unique_objects": unique_objects,"unique_confidence_scores": unique_scores}except Exception as e:error_msg = f"Error processing URL: {str(e)}"logger.error(f"{error_msg}\n{traceback.format_exc()}")return {"error": error_msg}url_submit_btn.click(fn=process_url_for_gradio,inputs=[image_url_input, url_model_choice],outputs=[url_output])with gr.Tab("βΉοΈ Help"):gr.Markdown("""## How to Use- **Image Upload**: Select a model, upload an image or provide a URL, and click "Detect" to see detected objects and image properties.- **URL Input**: Enter an image URL, select a model, and click "Process URL" to get results in JSON format.- **Models**: Choose from DETR (object detection or panoptic segmentation) or YOLOS (lightweight detection).- **Clear**: Reset all inputs and outputs using the "Clear" button.- **Errors**: Check the error box for any processing issues.## Tips- Use high-quality images for better detection results.- Panoptic models (e.g., DETR-ResNet-50-panoptic) provide segmentation masks for complex scenes.- For faster processing, try YOLOS-Tiny on resource-constrained devices.""")return demoif __name__ == "__main__":demo = create_gradio_ui()demo.launch()# To run FastAPI, use: uvicorn object_detection:app --host 0.0.0.0 --port 80001234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651663 unmodified lines17017117217317417517617 unmodified lines1941951961971981992 unmodified lines2022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822835 unmodified lines289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742import argparseimport base64import loggingimport osimport sysimport tracebackimport threadingfrom collections import Counterfrom io import BytesIOfrom typing import Dict, List, Optional, Tupleimport gradio as grimport pandas as pdimport requestsimport torchimport uvicornfrom fastapi import FastAPI, File, Form, HTTPException, UploadFilefrom fastapi.responses import JSONResponsefrom PIL import Image, ImageDraw, ImageStatfrom transformers import (DetrForObjectDetection,DetrForSegmentation,DetrImageProcessor,YolosForObjectDetection,YolosImageProcessor,)import nest_asyncio# ------------------------------# Configuration# ------------------------------# Logging configurationlogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(levelname)s - %(message)s",)logger = logging.getLogger(__name__)# Model and processing constantsCONFIDENCE_THRESHOLD: float = 0.5VALID_MODELS: List[str] = ["facebook/detr-resnet-50","facebook/detr-resnet-101","facebook/detr-resnet-50-panoptic","facebook/detr-resnet-101-panoptic","hustvl/yolos-tiny","hustvl/yolos-base",]MODEL_DESCRIPTIONS: Dict[str, str] = {"facebook/detr-resnet-50": ("DETR with ResNet-50 backbone for object detection. Fast and accurate for general use."),"facebook/detr-resnet-101": ("DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50."),"facebook/detr-resnet-50-panoptic": ("DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes."),"facebook/detr-resnet-101-panoptic": ("DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes."),"hustvl/yolos-tiny": ("YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments."),"hustvl/yolos-base": ("YOLOS Base model. Balances speed and accuracy for object detection."),}# Port configurationDEFAULT_GRADIO_PORT: int = 7860DEFAULT_FASTAPI_PORT: int = 8000PORT_RANGE: range = range(7860, 7870) # Try ports 7860-7869MAX_PORT_ATTEMPTS: int = 10# Thread-safe storage for lazy-loaded models and processorsmodels: Dict[str, any] = {}processors: Dict[str, any] = {}model_lock = threading.Lock()# ------------------------------# Model Loading# ------------------------------def load_model_and_processor(model_name: str) -> Tuple[any, any]:"""Load and cache the specified model and processor thread-safely.Args:model_name: Name of the model to load (must be in VALID_MODELS).Returns:Tuple containing the loaded model and processor.Raises:ValueError: If the model_name is invalid or loading fails."""with model_lock:if model_name not in models:logger.info(f"Loading model: {model_name}")try:if "yolos" in model_name:models[model_name] = YolosForObjectDetection.from_pretrained(model_name)processors[model_name] = YolosImageProcessor.from_pretrained(model_name)elif "panoptic" in model_name:models[model_name] = DetrForSegmentation.from_pretrained(model_name)processors[model_name] = DetrImageProcessor.from_pretrained(model_name)else:models[model_name] = DetrForObjectDetection.from_pretrained(model_name)processors[model_name] = DetrImageProcessor.from_pretrained(model_name)logger.debug(f"Model {model_name} loaded successfully")except Exception as e:logger.error(f"Failed to load model {model_name}: {str(e)}")raise ValueError(f"Failed to load model: {str(e)}")return models[model_name], processors[model_name]# ------------------------------# Image Processing# ------------------------------def process(image: Image.Image, model_name: str) -> Tuple[Image.Image, List[str], List[float], List[str], List[float], Dict[str, str]]:"""Process an image for object detection or panoptic segmentation.Args:image: PIL Image to process.model_name: Name of the model to use (must be in VALID_MODELS).Returns:Tuple containing:- Annotated image (PIL Image).- List of detected object names.- List of confidence scores for detected objects.- List of unique object names.- List of confidence scores for unique objects.- Dictionary of image properties (format, size, etc.).Raises:ValueError: If the model_name is invalid.RuntimeError: If processing fails due to model or image issues."""if model_name not in VALID_MODELS:raise ValueError(f"Invalid model: {model_name}. Choose from: {VALID_MODELS}")try:# Load model and processormodel, processor = load_model_and_processor(model_name)logger.debug(f"Processing image with model: {model_name}")# Prepare image for processinginputs = processor(images=image, return_tensors="pt")with torch.no_grad():outputs = model(**inputs)# Initialize drawing contextdraw = ImageDraw.Draw(image)object_names: List[str] = []confidence_scores: List[float] = []object_counter = Counter()target_sizes = torch.tensor([image.size[::-1]])# Process panoptic segmentation or object detectionif "panoptic" in model_name:processed_sizes = torch.tensor([[inputs["pixel_values"].shape[2], inputs["pixel_values"].shape[3]]])results = processor.post_process_panoptic(outputs, target_sizes=target_sizes, processed_sizes=processed_sizes)[0]3 unmodified lineslabel_name = model.config.id2label.get(label, "Unknown")score = segment.get("score", 1.0)# Apply segmentation mask if availableif "masks" in results and segment["id"] < len(results["masks"]):mask = results["masks"][segment["id"]].cpu().numpy()if mask.shape[0] > 0 and mask.shape[1] > 0:17 unmodified linesx, y, x2, y2 = box.tolist()draw.rectangle([x, y, x2, y2], outline="#32CD32", width=2)label_name = model.config.id2label.get(label.item(), "Unknown")text = f"{label_name}: {score:.2f}"text_bbox = draw.textbbox((0, 0), text)text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]2 unmodified linesconfidence_scores.append(float(score))object_counter[label_name] = float(score)# Compile unique objects and confidencesunique_objects = list(object_counter.keys())unique_confidences = [object_counter[obj] for obj in unique_objects]# Calculate image propertiesproperties: Dict[str, str] = {"Format": image.format if hasattr(image, "format") and image.format else "Unknown","Size": f"{image.width}x{image.height}","Width": f"{image.width} px","Height": f"{image.height} px","Mode": image.mode,"Aspect Ratio": (f"{round(image.width / image.height, 2)}" if image.height != 0 else "Undefined"),"File Size": "Unknown","Mean (R,G,B)": "Unknown","StdDev (R,G,B)": "Unknown",}# Compute file sizetry:buffered = BytesIO()image.save(buffered, format="PNG")properties["File Size"] = f"{len(buffered.getvalue()) / 1024:.2f} KB"except Exception as e:logger.error(f"Error calculating file size: {str(e)}")# Compute color statisticstry:stat = ImageStat.Stat(image)properties["Mean (R,G,B)"] = ", ".join(f"{m:.2f}" for m in stat.mean)properties["StdDev (R,G,B)"] = ", ".join(f"{s:.2f}" for s in stat.stddev)except Exception as e:logger.error(f"Error calculating color statistics: {str(e)}")return image, object_names, confidence_scores, unique_objects, unique_confidences, propertiesexcept Exception as e:logger.error(f"Error in process: {str(e)}\n{traceback.format_exc()}")raise RuntimeError(f"Failed to process image: {str(e)}")# ------------------------------# FastAPI Setup# ------------------------------app = FastAPI(title="Object Detection API")@app.post("/detect")async def detect_objects_endpoint(file: Optional[UploadFile] = File(None),image_url: Optional[str] = Form(None),model_name: str = Form(VALID_MODELS[0]),) -> JSONResponse:"""FastAPI endpoint to detect objects in an image from file upload or URL.Args:file: Uploaded image file (optional).image_url: URL of the image (optional).model_name: Model to use for detection (default: first VALID_MODELS entry).Returns:JSONResponse containing the processed image (base64), detected objects, and confidences.Raises:HTTPException: If input validation fails or processing errors occur."""try:# Validate inputif (file is None and not image_url) or (file is not None and image_url):raise HTTPException(status_code=400,detail="Provide either an image file or an image URL, not both.",)# Load imageif file:if not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="File must be an image")5 unmodified linesimage = Image.open(BytesIO(response.content)).convert("RGB")if model_name not in VALID_MODELS:raise HTTPException(status_code=400,detail=f"Invalid model. Choose from: {VALID_MODELS}",)# Process imagedetected_image, detected_objects, detected_confidences, unique_objects, unique_confidences, _ = process(image, model_name)# Encode image as base64buffered = BytesIO()detected_image.save(buffered, format="PNG")img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")img_url = f"data:image/png;base64,{img_base64}"return JSONResponse(content={"image_url": img_url,"detected_objects": detected_objects,"confidence_scores": detected_confidences,"unique_objects": unique_objects,"unique_confidence_scores": unique_confidences,})except requests.RequestException as e:logger.error(f"Error fetching image from URL: {str(e)}")raise HTTPException(status_code=400, detail=f"Failed to fetch image: {str(e)}")except Exception as e:logger.error(f"Error in FastAPI endpoint: {str(e)}\n{traceback.format_exc()}")raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")# ------------------------------# Gradio UI Setup# ------------------------------def create_gradio_ui() -> gr.Blocks:"""Create and configure the Gradio UI for object detection.Returns:Gradio Blocks object representing the UI.Raises:RuntimeError: If UI creation fails."""try:with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="gray")) as app:gr.Markdown(f"""# π Object Detection AppUpload an image or provide a URL to detect objects using state-of-the-art transformer models (DETR, YOLOS).Running on port: {os.getenv('GRADIO_SERVER_PORT', 'auto-selected')}""")with gr.Tabs():with gr.Tab("π· Image Upload"):with gr.Row():with gr.Column(scale=1):gr.Markdown("### Input")model_choice = gr.Dropdown(choices=VALID_MODELS,value=VALID_MODELS[0],label="π Select Model",info="Choose a model for object detection or panoptic segmentation.",)model_info = gr.Markdown(f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}",visible=True,)image_input = gr.Image(type="pil", label="π· Upload Image")image_url_input = gr.Textbox(label="π Image URL",placeholder="https://example.com/image.jpg",)with gr.Row():submit_btn = gr.Button("β¨ Detect", variant="primary")clear_btn = gr.Button("ποΈ Clear", variant="secondary")model_choice.change(fn=lambda model_name: (f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}"),inputs=model_choice,outputs=model_info,)with gr.Column(scale=2):gr.Markdown("### Results")error_output = gr.Textbox(label="β οΈ Errors",visible=False,lines=3,max_lines=5,)output_image = gr.Image(type="pil",label="π― Detected Image",interactive=False,)with gr.Row():objects_output = gr.DataFrame(label="π Detected Objects",interactive=False,value=None,)unique_objects_output = gr.DataFrame(label="π Unique Objects",interactive=False,value=None,)properties_output = gr.DataFrame(label="π Image Properties",interactive=False,value=None,)def process_for_gradio(image: Optional[Image.Image], url: Optional[str], model_name: str) -> Tuple[Optional[Image.Image], Optional[pd.DataFrame], Optional[pd.DataFrame], Optional[pd.DataFrame], str]:"""Process image for Gradio UI and return results.Args:image: Uploaded PIL Image (optional).url: Image URL (optional).model_name: Model to use for detection.Returns:Tuple of detected image, objects DataFrame, unique objects DataFrame, properties DataFrame, and error message."""try:if image is None and not url:return None, None, None, None, "Please provide an image or URL"if image and url:return None, None, None, None, "Please provide either an image or URL, not both"if url:response = requests.get(url, timeout=10)response.raise_for_status()image = Image.open(BytesIO(response.content)).convert("RGB")detected_image, objects, scores, unique_objects, unique_scores, properties = process(image, model_name)objects_df = (pd.DataFrame({"Object": objects,"Confidence Score": [f"{score:.2f}" for score in scores],})if objectselse pd.DataFrame(columns=["Object", "Confidence Score"]))unique_objects_df = (pd.DataFrame({"Unique Object": unique_objects,"Confidence Score": [f"{score:.2f}" for score in unique_scores],})if unique_objectselse pd.DataFrame(columns=["Unique Object", "Confidence Score"]))properties_df = (pd.DataFrame([properties])if propertieselse pd.DataFrame(columns=properties.keys()))return detected_image, objects_df, unique_objects_df, properties_df, ""except requests.RequestException as e:error_msg = f"Error fetching image from URL: {str(e)}"logger.error(f"{error_msg}\n{traceback.format_exc()}")return None, None, None, None, error_msgexcept Exception as e:error_msg = f"Error processing image: {str(e)}"logger.error(f"{error_msg}\n{traceback.format_exc()}")return None, None, None, None, error_msgsubmit_btn.click(fn=process_for_gradio,inputs=[image_input, image_url_input, model_choice],outputs=[output_image, objects_output, unique_objects_output, properties_output, error_output],)clear_btn.click(fn=lambda: [None, "", None, None, None, None],inputs=None,outputs=[image_input,image_url_input,output_image,objects_output,unique_objects_output,properties_output,error_output,],)with gr.Tab("π JSON Output"):gr.Markdown("### Process Image for JSON Output")image_input_json = gr.Image(type="pil", label="π· Upload Image")image_url_input_json = gr.Textbox(label="π Image URL",placeholder="https://example.com/image.jpg",)url_model_choice = gr.Dropdown(choices=VALID_MODELS,value=VALID_MODELS[0],label="π Select Model",)url_model_info = gr.Markdown(f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}",visible=True,)url_submit_btn = gr.Button("π Process", variant="primary")url_output = gr.JSON(label="API Response")url_model_choice.change(fn=lambda model_name: (f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}"),inputs=url_model_choice,outputs=url_model_info,)def process_url_for_gradio(image: Optional[Image.Image], url: Optional[str], model_name: str) -> Dict:"""Process image from file or URL for Gradio UI and return JSON response.Args:image: Uploaded PIL Image (optional).url: Image URL (optional).model_name: Model to use for detection.Returns:Dictionary with processed image (base64), detected objects, and confidences."""try:if image is None and not url:return {"error": "Please provide an image or URL"}if image and url:return {"error": "Please provide either an image or URL, not both"}if url:response = requests.get(url, timeout=10)response.raise_for_status()image = Image.open(BytesIO(response.content)).convert("RGB")detected_image, objects, scores, unique_objects, unique_scores, _ = process(image, model_name)buffered = BytesIO()detected_image.save(buffered, format="PNG")img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")return {"image_url": f"data:image/png;base64,{img_base64}","detected_objects": objects,"confidence_scores": scores,"unique_objects": unique_objects,"unique_confidence_scores": unique_scores,}except requests.RequestException as e:error_msg = f"Error fetching image from URL: {str(e)}"logger.error(f"{error_msg}\n{traceback.format_exc()}")return {"error": error_msg}except Exception as e:error_msg = f"Error processing image: {str(e)}"logger.error(f"{error_msg}\n{traceback.format_exc()}")return {"error": error_msg}url_submit_btn.click(fn=process_url_for_gradio,inputs=[image_input_json, image_url_input_json, url_model_choice],outputs=[url_output],)with gr.Tab("βΉοΈ Help"):gr.Markdown("""## How to Use- **Image Upload**: Select a model, upload an image or provide a URL, and click "Detect" to see detected objects and image properties.- **JSON Output**: Upload an image or enter a URL, select a model, and click "Process" to get results in JSON format.- **Models**: Choose from DETR (object detection or panoptic segmentation) or YOLOS (lightweight detection).- **Clear**: Reset all inputs and outputs using the "Clear" button in the Image Upload tab.- **Errors**: Check the error box (Image Upload) or JSON response (JSON Output) for issues.## Tips- Use high-quality images for better detection results.- Panoptic models (e.g., DETR-ResNet-50-panoptic) provide segmentation masks for complex scenes.- For faster processing, try YOLOS-Tiny on resource-constrained devices.""")return appexcept Exception as e:logger.error(f"Error creating Gradio UI: {str(e)}\n{traceback.format_exc()}")raise RuntimeError(f"Failed to create Gradio UI: {str(e)}")# ------------------------------# Launcher# ------------------------------def parse_args() -> argparse.Namespace:"""Parse command-line arguments with defaults and ignore unrecognized arguments.Returns:Parsed arguments as a Namespace object.Raises:SystemExit: If argument parsing fails (handled by argparse)."""parser = argparse.ArgumentParser(description="Launcher for Object Detection App with Gradio UI and optional FastAPI server.")parser.add_argument("--gradio-port",type=int,default=DEFAULT_GRADIO_PORT,help=f"Port for the Gradio UI (default: {DEFAULT_GRADIO_PORT}).",)parser.add_argument("--enable-fastapi",action="store_true",default=False,help="Enable the FastAPI server (disabled by default).",)parser.add_argument("--fastapi-port",type=int,default=DEFAULT_FASTAPI_PORT,help=f"Port for the FastAPI server if enabled (default: {DEFAULT_FASTAPI_PORT}).",)# Parse known arguments and ignore unrecognized ones (e.g., Jupyter kernel args)args, _ = parser.parse_known_args()return argsdef find_available_port(start_port: int, port_range: range, max_attempts: int) -> Optional[int]:"""Find an available port within the specified range.Args:start_port: Initial port to try (e.g., from args or environment).port_range: Range of ports to attempt.max_attempts: Maximum number of ports to try.Returns:Available port number, or None if no port is found.Raises:OSError: If port binding fails for reasons other than port in use."""import socketport = start_portattempts = 0# Check environment variable GRADIO_SERVER_PORTenv_port = os.getenv("GRADIO_SERVER_PORT")if env_port and env_port.isdigit():port = int(env_port)logger.info(f"Using GRADIO_SERVER_PORT from environment: {port}")while attempts < max_attempts:with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:try:s.bind(("0.0.0.0", port))logger.debug(f"Port {port} is available")return portexcept OSError as e:if e.errno == 98: # Port in uselogger.debug(f"Port {port} is in use")port = port + 1 if port < max(port_range) else min(port_range)attempts += 1else:raiseexcept Exception as e:logger.error(f"Error checking port {port}: {str(e)}")raiselogger.error(f"No available port found in range {min(port_range)}-{max(port_range)} after {max_attempts} attempts")return Nonedef run_fastapi_server(host: str, port: int) -> None:"""Run the FastAPI server using Uvicorn.Args:host: Host address for the FastAPI server.port: Port for the FastAPI server."""try:uvicorn.run(app, host=host, port=port)except Exception as e:logger.error(f"Error running FastAPI server: {str(e)}\n{traceback.format_exc()}")sys.exit(1)def main() -> None:"""Main function to launch Gradio UI and optional FastAPI server.Raises:SystemExit: If the application is interrupted or encounters an error."""try:# Apply nest_asyncio to allow nested event loops in Jupyter/Colabnest_asyncio.apply()# Parse command-line argumentsargs = parse_args()logger.info(f"Parsed arguments: {args}")# Find available port for Gradiogradio_port = find_available_port(args.gradio_port, PORT_RANGE, MAX_PORT_ATTEMPTS)if gradio_port is None:logger.error("Failed to find an available port for Gradio UI")sys.exit(1)# Launch FastAPI server in a separate thread if enabledif args.enable_fastapi:logger.info(f"Starting FastAPI server on port {args.fastapi_port}")fastapi_thread = threading.Thread(target=run_fastapi_server,args=("0.0.0.0", args.fastapi_port),daemon=True)fastapi_thread.start()# Launch Gradio UIlogger.info(f"Starting Gradio UI on port {gradio_port}")app = create_gradio_ui()app.launch(server_port=gradio_port, server_name="0.0.0.0")except KeyboardInterrupt:logger.info("Application terminated by user.")sys.exit(0)except OSError as e:logger.error(f"Port binding error: {str(e)}")sys.exit(1)except Exception as e:logger.error(f"Error running application: {str(e)}\n{traceback.format_exc()}")sys.exit(1)if __name__ == "__main__":main()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253541 unmodified line56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421435 unmodified lines1491501511521531541551561571581591601611623 unmodified lines166167168169170171172173174175176177178179180181182183184185# π Object Detection with Transformer ModelsThis project provides an object detection system using state-of-the-art transformer models, such as **DETR (DEtection TRansformer)** and **YOLOS (You Only Look One-level Series)**. The system can detect objects from uploaded images or image URLs, and it supports different models for detection and segmentation tasks. It includes a Gradio-based web interface and a FastAPI-based API for programmatic access.You can try the demo online on Hugging Face: [Demo Link](https://huggingface.co/spaces/NeerajCodz/ObjectDetection).## Models SupportedThe following models are supported, as defined in the application:- **DETR (DEtection TRansformer)**:- `facebook/detr-resnet-50`: DETR with ResNet-50 backbone for object detection. Fast and accurate for general use.- `facebook/detr-resnet-101`: DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50.- `facebook/detr-resnet-50-panoptic`(currently has bugs): DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes.- `facebook/detr-resnet-101-panoptic`(currently has bugs): DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes.- **YOLOS (You Only Look One-level Series)**:- `hustvl/yolos-tiny`: YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments.- `hustvl/yolos-base`: YOLOS Base model. Balances speed and accuracy for object detection.## Features- **Image Upload**: Upload images from your device for object detection via the Gradio interface.- **URL Input**: Input an image URL for detection through the Gradio interface or API.- **Model Selection**: Choose between DETR and YOLOS models for detection or panoptic segmentation.- **Object Detection**: Detects objects and highlights them with bounding boxes and confidence scores.- **Panoptic Segmentation**: Some models (e.g., DETR panoptic variants) support detailed scene segmentation with colored masks.- **Image Properties**: Displays image metadata such as format, size, aspect ratio, file size, and color statistics.- **API Access**: Use the FastAPI endpoint `/detect` to programmatically process images and retrieve detection results.## How to Use### 1. **Normal Git Clone Method**Follow these steps to set up the application locally:#### Prerequisites- Python 3.8 or higher- Install dependencies using `pip`#### Clone the Repository```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```#### Install DependenciesInstall the required dependencies from `requirements.txt`:```bashpip install -r requirements.txt1 unmodified line#### Run the ApplicationStart the FastAPI server using uvicorn:```bashuvicorn objectdetection:app --reload```Alternatively, launch the Gradio interface by running the main script:```bashpython app.py```#### Access the Application- For FastAPI: Open your browser and navigate to `http://localhost:8000` to use the API or view the Swagger UI.- For Gradio: The Gradio interface URL will be displayed in the console (typically `http://127.0.0.1:7860`).### 2. **Running with Docker**If you prefer to use Docker to set up and run the application, follow these steps:#### Prerequisites- Docker installed on your machine. If you donβt have Docker, download and install it from [here](https://www.docker.com/get-started).#### Build the Docker ImageFirst, clone the repository (if you haven't already):```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```Now, build the Docker image:```bashdocker build -t objectdetection:latest .```#### Run the Docker ContainerOnce the image is built, run the application using this command:```bashdocker run -p 5000:5000 objectdetection:latest```This will start the application on port 5000. Open your browser and go to `http://localhost:5000` to access the FastAPI interface.### 3. **Demo**You can try the demo directly online through Hugging Face's Spaces:[Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection)## Using the APIYou can interact with the application via the FastAPI `/detect` endpoint to send images and get detection results.**Endpoint**: `/detect`**POST**: `/detect`**Parameters**:- `file`: (optional) Image file (must be of type `image/*`).- `image_url`: (optional) URL of the image.- `model_name`: (optional) Choose from `facebook/detr-resnet-50`, `hustvl/yolos-tiny`, etc.**Example Request Body**:```json{"image_url": "https://example.com/image.jpg","model_name": "facebook/detr-resnet-50"}```**Response**:The response includes a base64-encoded image with detections, detected objects, confidence scores, and unique objects with their scores.```json{5 unmodified lines}```## Development SetupIf you'd like to contribute or modify the application:1. Clone the repository:```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```3 unmodified linespip install -r requirements.txt```3. Run the FastAPI server or Gradio interface:```bashuvicorn objectdetection:app --reload```or```bashpython app.py```4. Open your browser and navigate to `http://localhost:8000` (FastAPI) or the Gradio URL (typically `http://127.0.0.1:7860`).## ContributingContributions are welcome! Feel free to open issues or submit pull requests for bug fixes or new features on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455561 unmodified line5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062075 unmodified lines2132142152162172182192202212222232242252262272282292302312323 unmodified lines236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272# π Object Detection with Transformer ModelsThis project provides a robust object detection system leveraging state-of-the-art transformer models, including **DETR (DEtection TRansformer)** and **YOLOS (You Only Look One-level Series)**. The system supports object detection and panoptic segmentation from uploaded images or image URLs. It features a user-friendly **Gradio** web interface for interactive use and a **FastAPI** endpoint for programmatic access.Try the online demo on Hugging Face Spaces: [Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection).## Models SupportedThe application supports the following models, each tailored for specific detection or segmentation tasks:- **DETR (DEtection TRansformer)**:- `facebook/detr-resnet-50`: Fast and accurate object detection with a ResNet-50 backbone.- `facebook/detr-resnet-101`: Higher accuracy object detection with a ResNet-101 backbone, slower than ResNet-50.- `facebook/detr-resnet-50-panoptic`: Panoptic segmentation with ResNet-50 (note: may have stability issues).- `facebook/detr-resnet-101-panoptic`: Panoptic segmentation with ResNet-101 (note: may have stability issues).- **YOLOS (You Only Look One-level Series)**:- `hustvl/yolos-tiny`: Lightweight and fast, ideal for resource-constrained environments.- `hustvl/yolos-base`: Balances speed and accuracy for object detection.## Features- **Image Upload**: Upload images via the Gradio interface for object detection.- **URL Input**: Provide image URLs for detection through the Gradio interface or API.- **Model Selection**: Choose between DETR and YOLOS models for detection or panoptic segmentation.- **Object Detection**: Highlights detected objects with bounding boxes and confidence scores.- **Panoptic Segmentation**: Supports scene segmentation with colored masks (DETR panoptic models).- **Image Properties**: Displays metadata like format, size, aspect ratio, file size, and color statistics.- **API Access**: Programmatically process images via the FastAPI `/detect` endpoint.- **Flexible Deployment**: Run locally, in Docker, or in cloud environments like Google Colab.## How to Use### 1. **Local Setup (Git Clone)**Follow these steps to set up the application locally:#### Prerequisites- Python 3.8 or higher- `pip` for installing dependencies- Git for cloning the repository#### Clone the Repository```bashgit clone https://github.com/NeerajCodz/ObjectDetectioncd ObjectDetection```#### Install DependenciesInstall required packages from `requirements.txt`:```bashpip install -r requirements.txt1 unmodified line#### Run the ApplicationLaunch the Gradio interface:```bashpython app.py```To enable the FastAPI server:```bashpython app.py --enable-fastapi```#### Access the Application- **Gradio**: Open the URL displayed in the console (typically `http://127.0.0.1:7860`).- **FastAPI**: Navigate to `http://localhost:8000` for the API or Swagger UI (if enabled).### 2. **Running with Docker**Use Docker for a containerized setup.#### Prerequisites- Docker installed on your machine. Download from [Docker's official site](https://www.docker.com/get-started).#### Pull the Docker ImagePull the pre-built image from Docker Hub:```bashdocker pull neerajcodz/objectdetection:latest```#### Run the Docker ContainerRun the application on port 8080:```bashdocker run -d -p 8080:80 neerajcodz/objectdetection:latest```Access the interface at `http://localhost:8080`.#### Build and Run the Docker ImageTo build the Docker image locally:1. Ensure you have a `Dockerfile` in the repository root (example provided in the repository).2. Build the image:```bashdocker build -t objectdetection:local .```3. Run the container:```bashdocker run -d -p 8080:80 objectdetection:local```Access the interface at `http://localhost:8080`.### 3. **Demo**Try the demo on Hugging Face Spaces:[Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection)## Command-Line ArgumentsThe `app.py` script supports the following command-line arguments:- `--gradio-port <port>`: Specify the port for the Gradio UI (default: 7860).- Example: `python app.py --gradio-port 7870`- `--enable-fastapi`: Enable the FastAPI server (disabled by default).- Example: `python app.py --enable-fastapi`- `--fastapi-port <port>`: Specify the port for the FastAPI server (default: 8000).- Example: `python app.py --enable-fastapi --fastapi-port 8001`You can combine arguments:```bashpython app.py --gradio-port 7870 --enable-fastapi --fastapi-port 8001```Alternatively, set the `GRADIO_SERVER_PORT` environment variable:```bashexport GRADIO_SERVER_PORT=7870python app.py```## Using the API**Note**: The FastAPI API is currently unstable and may require additional configuration for production use.The `/detect` endpoint allows programmatic image processing.### Running the FastAPI ServerEnable FastAPI when launching the script:```bashpython app.py --enable-fastapi```Or run FastAPI separately with Uvicorn:```bashuvicorn objectdetection:app --host 0.0.0.0 --port 8000```Access the Swagger UI at `http://localhost:8000/docs` for interactive testing.### Endpoint Details- **Endpoint**: `POST /detect`- **Parameters**:- `file`: (optional) Image file (must be `image/*` type).- `image_url`: (optional) URL of the image.- `model_name`: (optional) Model name (e.g., `facebook/detr-resnet-50`, `hustvl/yolos-tiny`).- **Content-Type**: `multipart/form-data` for file uploads, `application/json` for URL inputs.### Example Requests#### Using `curl` with an Image URL```bashcurl -X POST "http://localhost:8000/detect" \-H "Content-Type: application/json" \-d '{"image_url": "https://example.com/image.jpg", "model_name": "facebook/detr-resnet-50"}'```#### Using `curl` with an Image File```bashcurl -X POST "http://localhost:8000/detect" \-F "file=@/path/to/image.jpg" \-F "model_name=facebook/detr-resnet-50"```### Response FormatThe response includes a base64-encoded image with detections and detection details:```json{5 unmodified lines}```### Notes- Ensure only one of `file` or `image_url` is provided.- The API may experience instability with panoptic models; use object detection models for reliability.- Test the API using the Swagger UI for easier debugging.## Development SetupTo contribute or modify the application:1. Clone the repository:```bashgit clone https://github.com/NeerajCodz/ObjectDetectioncd ObjectDetection```3 unmodified linespip install -r requirements.txt```3. Run the application:```bashpython app.py```Or run FastAPI:```bashuvicorn objectdetection:app --host 0.0.0.0 --port 8000```4. Access at `http://localhost:7860` (Gradio) or `http://localhost:8000` (FastAPI).## ContributingContributions are welcome! To contribute:1. Fork the repository.2. Create a feature or bugfix branch (`git checkout -b feature/your-feature`).3. Commit changes (`git commit -m "Add your feature"`).4. Push to the branch (`git push origin feature/your-feature`).5. Open a pull request on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).Please include tests and documentation for new features. Report issues via GitHub Issues.## Troubleshooting- **Port Conflicts**: If port 7860 is in use, specify a different port with `--gradio-port` or set `GRADIO_SERVER_PORT`.- **Colab Issues**: Use the `--gradio-port` argument or environment variable to avoid port conflicts in Google Colab.- **Panoptic Model Bugs**: Avoid `detr-resnet-*-panoptic` models until stability issues are resolved.- **API Instability**: Test with smaller images and object detection models first.For further assistance, open an issue on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).
123456789101112---title: ObjectDetectionemoji: π¦colorFrom: greencolorTo: yellowsdk: gradiosdk_version: 5.29.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185# π Object Detection with Transformer ModelsThis project provides an object detection system using state-of-the-art transformer models, such as **DETR (DEtection TRansformer)** and **YOLOS (You Only Look One-level Series)**. The system can detect objects from uploaded images or image URLs, and it supports different models for detection and segmentation tasks. It includes a Gradio-based web interface and a FastAPI-based API for programmatic access.You can try the demo online on Hugging Face: [Demo Link](https://huggingface.co/spaces/NeerajCodz/ObjectDetection).## Models SupportedThe following models are supported, as defined in the application:- **DETR (DEtection TRansformer)**:- `facebook/detr-resnet-50`: DETR with ResNet-50 backbone for object detection. Fast and accurate for general use.- `facebook/detr-resnet-101`: DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50.- `facebook/detr-resnet-50-panoptic`(currently has bugs): DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes.- `facebook/detr-resnet-101-panoptic`(currently has bugs): DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes.- **YOLOS (You Only Look One-level Series)**:- `hustvl/yolos-tiny`: YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments.- `hustvl/yolos-base`: YOLOS Base model. Balances speed and accuracy for object detection.## Features- **Image Upload**: Upload images from your device for object detection via the Gradio interface.- **URL Input**: Input an image URL for detection through the Gradio interface or API.- **Model Selection**: Choose between DETR and YOLOS models for detection or panoptic segmentation.- **Object Detection**: Detects objects and highlights them with bounding boxes and confidence scores.- **Panoptic Segmentation**: Some models (e.g., DETR panoptic variants) support detailed scene segmentation with colored masks.- **Image Properties**: Displays image metadata such as format, size, aspect ratio, file size, and color statistics.- **API Access**: Use the FastAPI endpoint `/detect` to programmatically process images and retrieve detection results.## How to Use### 1. **Normal Git Clone Method**Follow these steps to set up the application locally:#### Prerequisites- Python 3.8 or higher- Install dependencies using `pip`#### Clone the Repository```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```#### Install DependenciesInstall the required dependencies from `requirements.txt`:```bashpip install -r requirements.txt```#### Run the ApplicationStart the FastAPI server using uvicorn:```bashuvicorn objectdetection:app --reload```Alternatively, launch the Gradio interface by running the main script:```bashpython app.py```#### Access the Application- For FastAPI: Open your browser and navigate to `http://localhost:8000` to use the API or view the Swagger UI.- For Gradio: The Gradio interface URL will be displayed in the console (typically `http://127.0.0.1:7860`).### 2. **Running with Docker**If you prefer to use Docker to set up and run the application, follow these steps:#### Prerequisites- Docker installed on your machine. If you donβt have Docker, download and install it from [here](https://www.docker.com/get-started).#### Build the Docker ImageFirst, clone the repository (if you haven't already):```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```Now, build the Docker image:```bashdocker build -t objectdetection:latest .```#### Run the Docker ContainerOnce the image is built, run the application using this command:```bashdocker run -p 5000:5000 objectdetection:latest```This will start the application on port 5000. Open your browser and go to `http://localhost:5000` to access the FastAPI interface.### 3. **Demo**You can try the demo directly online through Hugging Face's Spaces:[Object Detection Demo](https://huggingface.co/spaces/NeerajCodz/ObjectDetection)## Using the APIYou can interact with the application via the FastAPI `/detect` endpoint to send images and get detection results.**Endpoint**: `/detect`**POST**: `/detect`**Parameters**:- `file`: (optional) Image file (must be of type `image/*`).- `image_url`: (optional) URL of the image.- `model_name`: (optional) Choose from `facebook/detr-resnet-50`, `hustvl/yolos-tiny`, etc.**Example Request Body**:```json{"image_url": "https://example.com/image.jpg","model_name": "facebook/detr-resnet-50"}```**Response**:The response includes a base64-encoded image with detections, detected objects, confidence scores, and unique objects with their scores.```json{"image_url": "data:image/png;base64,...","detected_objects": ["person", "car"],"confidence_scores": [0.95, 0.87],"unique_objects": ["person", "car"],"unique_confidence_scores": [0.95, 0.87]}```## Development SetupIf you'd like to contribute or modify the application:1. Clone the repository:```bashgit clone https://github.com/NeerajCodz/ObjectDetection.gitcd ObjectDetection```2. Install dependencies:```bashpip install -r requirements.txt```3. Run the FastAPI server or Gradio interface:```bashuvicorn objectdetection:app --reload```or```bashpython app.py```4. Open your browser and navigate to `http://localhost:8000` (FastAPI) or the Gradio URL (typically `http://127.0.0.1:7860`).## ContributingContributions are welcome! Feel free to open issues or submit pull requests for bug fixes or new features on the [GitHub repository](https://github.com/NeerajCodz/ObjectDetection).
1234567sdk: gradiopython_version: 3.10app_file: app.pytitle: Object Detection Appsubtitle: Real-time object detection in images using Gradiohardware: cpu-basiclicense: mit1234567891011121314151617181920212223242526name: Build and Push Docker Image to Docker Hub
on: push: branches: - main
jobs: build-and-push: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Log in to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PAT }}
- name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . push: true tags: ${{ secrets.DOCKER_USERNAME }}/objectdetection:latest123456789101112131415161718192021222324252627282930313233343536name: Sync to Hugging Face Space
on: push: branches: [ main ]
jobs: deploy-to-hf-space: runs-on: ubuntu-latest
steps: - name: Checkout Repository uses: actions/checkout@v3
- name: Install Git run: sudo apt-get install git
- name: Push to Hugging Face Space env: HF_TOKEN: ${{ secrets.HF_TOKEN }} HF_USERNAME: ${{ secrets.HF_USERNAME }} EMAIL: ${{ secrets.EMAIL }} run: | git config --global user.email $EMAIL git config --global user.name $HF_USERNAME git clone https://$HF_USERNAME:[email protected]/spaces/$HF_USERNAME/ObjectDetection hf_space rsync -av --exclude='.git' ./ hf_space/ cd hf_space git add . if git diff --cached --quiet; then echo "β
No changes to commit." else git commit -m "Sync from GitHub" git push fi12345__pycache__/venv/*.pyc.DS_Store.env12345678910111213FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]123456789101112131415161718192021MIT License
Copyright (c) 2025 Neeraj Sathish Kumar
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384import gradio as grimport torchfrom transformers import DetrImageProcessor, DetrForObjectDetectionfrom transformers import YolosImageProcessor, YolosForObjectDetectionfrom transformers import DetrForSegmentationfrom PIL import Image, ImageDraw, ImageStatimport requestsfrom io import BytesIOimport base64from collections import Counterimport loggingfrom fastapi import FastAPI, File, UploadFile, HTTPException, Formfrom fastapi.responses import JSONResponseimport uvicornimport pandas as pdimport tracebackimport os
# Set up logginglogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)
# ConstantsCONFIDENCE_THRESHOLD = 0.5VALID_MODELS = [ "facebook/detr-resnet-50", "facebook/detr-resnet-101", "facebook/detr-resnet-50-panoptic", "facebook/detr-resnet-101-panoptic", "hustvl/yolos-tiny", "hustvl/yolos-base"]MODEL_DESCRIPTIONS = { "facebook/detr-resnet-50": "DETR with ResNet-50 backbone for object detection. Fast and accurate for general use.", "facebook/detr-resnet-101": "DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50.", "facebook/detr-resnet-50-panoptic": "DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes.", "facebook/detr-resnet-101-panoptic": "DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes.", "hustvl/yolos-tiny": "YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments.", "hustvl/yolos-base": "YOLOS Base model. Balances speed and accuracy for object detection."}
# Lazy model loadingmodels = {}processors = {}
def process(image, model_name): """Process an image and return detected image, objects, confidences, unique objects, unique confidences, and properties.""" try: if model_name not in VALID_MODELS: raise ValueError(f"Invalid model: {model_name}. Choose from: {VALID_MODELS}")
# Load model and processor if model_name not in models: logger.info(f"Loading model: {model_name}") if "yolos" in model_name: models[model_name] = YolosForObjectDetection.from_pretrained(model_name) processors[model_name] = YolosImageProcessor.from_pretrained(model_name) elif "panoptic" in model_name: models[model_name] = DetrForSegmentation.from_pretrained(model_name) processors[model_name] = DetrImageProcessor.from_pretrained(model_name) else: models[model_name] = DetrForObjectDetection.from_pretrained(model_name) processors[model_name] = DetrImageProcessor.from_pretrained(model_name)
model, processor = models[model_name], processors[model_name] inputs = processor(images=image, return_tensors="pt")
with torch.no_grad(): outputs = model(**inputs)
target_sizes = torch.tensor([image.size[::-1]]) draw = ImageDraw.Draw(image) object_names = [] confidence_scores = [] object_counter = Counter()
if "panoptic" in model_name: processed_sizes = torch.tensor([[inputs["pixel_values"].shape[2], inputs["pixel_values"].shape[3]]]) results = processor.post_process_panoptic(outputs, target_sizes=target_sizes, processed_sizes=processed_sizes)[0]
for segment in results["segments_info"]: label = segment["label_id"] label_name = model.config.id2label.get(label, "Unknown") score = segment.get("score", 1.0)
if "masks" in results and segment["id"] < len(results["masks"]): mask = results["masks"][segment["id"]].cpu().numpy() if mask.shape[0] > 0 and mask.shape[1] > 0: mask_image = Image.fromarray((mask * 255).astype("uint8")) colored_mask = Image.new("RGBA", image.size, (0, 0, 0, 0)) mask_draw = ImageDraw.Draw(colored_mask) r, g, b = (segment["id"] * 50) % 255, (segment["id"] * 100) % 255, (segment["id"] * 150) % 255 mask_draw.bitmap((0, 0), mask_image, fill=(r, g, b, 128)) image = Image.alpha_composite(image.convert("RGBA"), colored_mask).convert("RGB") draw = ImageDraw.Draw(image)
if score > CONFIDENCE_THRESHOLD: object_names.append(label_name) confidence_scores.append(float(score)) object_counter[label_name] = float(score) else: results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)[0]
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): if score > CONFIDENCE_THRESHOLD: x, y, x2, y2 = box.tolist() draw.rectangle([x, y, x2, y2], outline="#32CD32", width=2) label_name = model.config.id2label.get(label.item(), "Unknown") # Place text at top-right corner, outside the box, with smaller size text = f"{label_name}: {score:.2f}" text_bbox = draw.textbbox((0, 0), text) text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1] draw.text((x2 - text_width - 2, y - text_height - 2), text, fill="#32CD32") object_names.append(label_name) confidence_scores.append(float(score)) object_counter[label_name] = float(score)
unique_objects = list(object_counter.keys()) unique_confidences = [object_counter[obj] for obj in unique_objects]
# Image properties file_size = "Unknown" if hasattr(image, "fp") and image.fp is not None: buffered = BytesIO() image.save(buffered, format="PNG") file_size = f"{len(buffered.getvalue()) / 1024:.2f} KB" # Color statistics try: stat = ImageStat.Stat(image) color_stats = { "mean": [f"{m:.2f}" for m in stat.mean], "stddev": [f"{s:.2f}" for s in stat.stddev] } except Exception as e: logger.error(f"Error calculating color statistics: {str(e)}") color_stats = {"mean": "Error", "stddev": "Error"}
properties = { "Format": image.format if hasattr(image, "format") and image.format else "Unknown", "Size": f"{image.width}x{image.height}", "Width": f"{image.width} px", "Height": f"{image.height} px", "Mode": image.mode, "Aspect Ratio": f"{round(image.width / image.height, 2) if image.height != 0 else 'Undefined'}", "File Size": file_size, "Mean (R,G,B)": ", ".join(color_stats["mean"]) if isinstance(color_stats["mean"], list) else color_stats["mean"], "StdDev (R,G,B)": ", ".join(color_stats["stddev"]) if isinstance(color_stats["stddev"], list) else color_stats["stddev"] }
return image, object_names, confidence_scores, unique_objects, unique_confidences, properties except Exception as e: logger.error(f"Error in process: {str(e)}\n{traceback.format_exc()}") raise
# FastAPI Setupapp = FastAPI(title="Object Detection API")
@app.post("/detect")async def detect_objects_endpoint( file: UploadFile = File(None), image_url: str = Form(None), model_name: str = Form(VALID_MODELS[0])): """FastAPI endpoint to detect objects in an image from file or URL.""" try: if (file is None and not image_url) or (file is not None and image_url): raise HTTPException(status_code=400, detail="Provide either an image file or an image URL, but not both.")
if file: if not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") contents = await file.read() image = Image.open(BytesIO(contents)).convert("RGB") else: response = requests.get(image_url, timeout=10) response.raise_for_status() image = Image.open(BytesIO(response.content)).convert("RGB")
if model_name not in VALID_MODELS: raise HTTPException(status_code=400, detail=f"Invalid model. Choose from: {VALID_MODELS}")
detected_image, detected_objects, detected_confidences, unique_objects, unique_confidences, _ = process(image, model_name)
buffered = BytesIO() detected_image.save(buffered, format="PNG") img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8") img_url = f"data:image/png;base64,{img_base64}"
return JSONResponse(content={ "image_url": img_url, "detected_objects": detected_objects, "confidence_scores": detected_confidences, "unique_objects": unique_objects, "unique_confidence_scores": unique_confidences }) except Exception as e: logger.error(f"Error in FastAPI endpoint: {str(e)}\n{traceback.format_exc()}") raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
# Gradio UIdef create_gradio_ui(): with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="gray")) as demo: gr.Markdown( """ # π Object Detection App Upload an image or provide a URL to detect objects using state-of-the-art transformer models (DETR, YOLOS). """ ) with gr.Tabs(): with gr.Tab("π· Image Upload"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Input") model_choice = gr.Dropdown( choices=VALID_MODELS, value=VALID_MODELS[0], label="π Select Model", info="Choose a model for object detection or panoptic segmentation." ) model_info = gr.Markdown( f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}", visible=True ) image_input = gr.Image(type="pil", label="π· Upload Image") image_url_input = gr.Textbox( label="π Image URL", placeholder="https://example.com/image.jpg" ) with gr.Row(): submit_btn = gr.Button("β¨ Detect", variant="primary") clear_btn = gr.Button("ποΈ Clear", variant="secondary") model_choice.change( fn=lambda model_name: f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}", inputs=model_choice, outputs=model_info ) with gr.Column(scale=2): gr.Markdown("### Results") error_output = gr.Textbox( label="β οΈ Errors", visible=False, lines=3, max_lines=5 ) output_image = gr.Image( type="pil", label="π― Detected Image", interactive=False ) with gr.Row(): objects_output = gr.DataFrame( label="π Detected Objects", interactive=False, value=None ) unique_objects_output = gr.DataFrame( label="π Unique Objects", interactive=False, value=None ) properties_output = gr.DataFrame( label="π Image Properties", interactive=False, value=None ) def process_for_gradio(image, url, model_name): try: if image is None and not url: return None, None, None, None, "Please provide an image or URL" if image and url: return None, None, None, None, "Please provide either an image or URL, not both" if url: response = requests.get(url, timeout=10) response.raise_for_status() image = Image.open(BytesIO(response.content)).convert("RGB") detected_image, objects, scores, unique_objects, unique_scores, properties = process(image, model_name) objects_df = pd.DataFrame({ "Object": objects, "Confidence Score": [f"{score:.2f}" for score in scores] }) if objects else pd.DataFrame(columns=["Object", "Confidence Score"]) unique_objects_df = pd.DataFrame({ "Unique Object": unique_objects, "Confidence Score": [f"{score:.2f}" for score in unique_scores] }) if unique_objects else pd.DataFrame(columns=["Unique Object", "Confidence Score"]) properties_df = pd.DataFrame([properties]) if properties else pd.DataFrame(columns=properties.keys()) return detected_image, objects_df, unique_objects_df, properties_df, "" except Exception as e: error_msg = f"Error processing image: {str(e)}" logger.error(f"{error_msg}\n{traceback.format_exc()}") return None, None, None, None, error_msg
submit_btn.click( fn=process_for_gradio, inputs=[image_input, image_url_input, model_choice], outputs=[output_image, objects_output, unique_objects_output, properties_output, error_output] ) clear_btn.click( fn=lambda: [None, "", None, None, None, None], inputs=None, outputs=[image_input, image_url_input, output_image, objects_output, unique_objects_output, properties_output, error_output] ) with gr.Tab("π URL Input"): gr.Markdown("### Process Image from URL") image_url_input = gr.Textbox( label="π Image URL", placeholder="https://example.com/image.jpg" ) url_model_choice = gr.Dropdown( choices=VALID_MODELS, value=VALID_MODELS[0], label="π Select Model" ) url_model_info = gr.Markdown( f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}", visible=True ) url_submit_btn = gr.Button("π Process URL", variant="primary") url_output = gr.JSON(label="API Response") url_model_choice.change( fn=lambda model_name: f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}", inputs=url_model_choice, outputs=url_model_info ) def process_url_for_gradio(url, model_name): try: response = requests.get(url, timeout=10) response.raise_for_status() image = Image.open(BytesIO(response.content)).convert("RGB") detected_image, objects, scores, unique_objects, unique_scores, _ = process(image, model_name) buffered = BytesIO() detected_image.save(buffered, format="PNG") img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8") return { "image_url": f"data:image/png;base64,{img_base64}", "detected_objects": objects, "confidence_scores": scores, "unique_objects": unique_objects, "unique_confidence_scores": unique_scores } except Exception as e: error_msg = f"Error processing URL: {str(e)}" logger.error(f"{error_msg}\n{traceback.format_exc()}") return {"error": error_msg}
url_submit_btn.click( fn=process_url_for_gradio, inputs=[image_url_input, url_model_choice], outputs=[url_output] ) with gr.Tab("βΉοΈ Help"): gr.Markdown( """ ## How to Use - **Image Upload**: Select a model, upload an image or provide a URL, and click "Detect" to see detected objects and image properties. - **URL Input**: Enter an image URL, select a model, and click "Process URL" to get results in JSON format. - **Models**: Choose from DETR (object detection or panoptic segmentation) or YOLOS (lightweight detection). - **Clear**: Reset all inputs and outputs using the "Clear" button. - **Errors**: Check the error box for any processing issues. ## Tips - Use high-quality images for better detection results. - Panoptic models (e.g., DETR-ResNet-50-panoptic) provide segmentation masks for complex scenes. - For faster processing, try YOLOS-Tiny on resource-constrained devices. """ )
return demo
if __name__ == "__main__": demo = create_gradio_ui() demo.launch() # To run FastAPI, use: uvicorn object_detection:app --host 0.0.0.0 --port 80001234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112---title: ObjectDetectionemoji: π¦colorFrom: greencolorTo: yellowsdk: gradiosdk_version: 5.29.0app_file: app.pypinned: false---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678transformerstorchtensorflowgradiopillowtimmfastapirequestsREADME.md+150-57
app.py+626-268
hf_space/README.md+148-61
hf_space/hf_space/README.md+185-12
hf_space/hf_space/hf_space/hf_space/hf_space/.huggingface.yamlAdded+7
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.github/workflows/docker-build-push.ymlAdded+26
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.github/workflows/hf-space-sync.ymlAdded+36
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.gitignoreAdded+5
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/DockerfileAdded+13
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/LICENSEAdded+21
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/app.pyAdded+384
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/.gitattributesAdded+35
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/README.mdAdded+12
hf_space/hf_space/hf_space/hf_space/hf_space/hf_space/requirements.txtAdded+8