Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| import cv2 | |
| from sklearn.neighbors import KNeighborsClassifier | |
| from sklearn.preprocessing import LabelEncoder | |
| # Load CSVs | |
| df_train = pd.read_csv("train_dataset.csv") | |
| # Split features and labels | |
| X_train = df_train.drop(columns=["label"]).values | |
| y_train = df_train["label"].values | |
| # Encode labels (if they're strings) | |
| le = LabelEncoder() | |
| y_train_encoded = le.fit_transform(y_train) | |
| # Train KNN | |
| knn = KNeighborsClassifier(n_neighbors=3) | |
| knn.fit(X_train, y_train_encoded) | |
| # Constants | |
| IMAGE_SIZE = 64 # should match training | |
| # Prediction function | |
| def predict_animal(image): | |
| # Convert image to grayscale and resize | |
| image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE)) | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| flat = gray.flatten().reshape(1, -1) | |
| # Predict | |
| pred_encoded = knn.predict(flat)[0] | |
| pred_label = le.inverse_transform([pred_encoded])[0] | |
| return pred_label | |
| # Gradio UI | |
| gr.Interface( | |
| fn=predict_animal, | |
| inputs=gr.Image(type="numpy", label="Upload Animal Image"), | |
| outputs=gr.Label(label="Predicted Animal"), | |
| title="Animal Classifier (KNN)", | |
| description="Upload an animal image to classify it using a KNN model trained on CSV data." | |
| ).launch() | |