Spaces:
Runtime error
Runtime error
Commit ·
b404ed5
1
Parent(s): 03a9dc8
Initial upload of Gradio app and baseline model
Browse filesFiles changed (5)
- app.pyAdded+116
- baseline.pyAdded+9
- models/herbarium_convnext_v2_base.pthAdded+3
- requirements.txtAdded+4
- species_list.txtAdded+100
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import gradio as grimport torchfrom torchvision import transformsfrom PIL import Imageimport osimport pandas as pd
# --- Model Loading ---def get_model_paths(): """Returns a dictionary of model names to their file paths.""" model_dir = "models" model_files = [f for f in os.listdir(model_dir) if f.endswith(".pth")] # You can create more descriptive names here if you want model_names = [os.path.splitext(f)[0] for f in model_files] return dict(zip(model_names, [os.path.join(model_dir, f) for f in model_files]))
MODEL_PATHS = get_model_paths()# Add placeholder paths for the other two modelsMODEL_PATHS["Future Model 1"] = "models/future_model_1.pth"MODEL_PATHS["Future Model 2"] = "models/future_model_2.pth"
# This is a placeholder for your actual model loading logic# You will need to replace this with the code to load your specific model architecturedef load_model(model_path): """Loads a model from the given path.""" # Example: # model = torch.load(model_path) # model.eval() # return model # For now, returning a dummy object print(f"Loading model from: {model_path}") if not os.path.exists(model_path): print("Warning: Model file does not exist. Using a dummy model.") return None # Replace with your actual model loading try: # This is a guess, you'll need to replace with your actual model class from baseline import convnext_v2_base model = convnext_v2_base(num_classes=10) # Or whatever your number of classes is model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu'))) model.eval() return model except Exception as e: print(f"Error loading model: {e}") print("Using a dummy model.") return None
# --- Image Preprocessing ---# You'll need to adjust this to match the preprocessing your model expectspreprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])
# --- Prediction ---# Load species listspecies_df = pd.read_csv('species_list.txt', sep=';', header=None, names=['class_id', 'species_name'])idx_to_class = {i: row['class_id'] for i, row in species_df.iterrows()}class_id_to_name = {row['class_id']: row['species_name'] for i, row in species_df.iterrows()}
def predict(model_name, image): """Makes a prediction on an image using the selected model.""" model_path = MODEL_PATHS[model_name] if not os.path.exists(model_path): return f"Model '{model_name}' not found. Please upload the model file."
model = load_model(model_path) if model is None: return f"Could not load model '{model_name}'."
pil_image = Image.fromarray(image.astype('uint8'), 'RGB') processed_image = preprocess(pil_image).unsqueeze(0)
with torch.no_grad(): outputs = model(processed_image).logits _, predicted_idx = torch.max(outputs, 1) class_id = idx_to_class[predicted_idx.item()] class_name = class_id_to_name[class_id] return f"Prediction: {class_name}"
# --- Gradio Interface ---with gr.Blocks() as demo: gr.Markdown("# Plant Classification") gr.Markdown("Select a model and upload an image to classify.")
with gr.Row(): model_dropdown = gr.Dropdown( choices=list(MODEL_PATHS.keys()), label="Select Model", value=list(MODEL_PATHS.keys())[0] if MODEL_PATHS else None ) image_input = gr.Image(type="numpy") output_text = gr.Textbox(label="Prediction")
image_input.change( fn=predict, inputs=[model_dropdown, image_input], outputs=output_text ) model_dropdown.change( fn=predict, inputs=[model_dropdown, image_input], outputs=output_text )
if __name__ == "__main__": demo.launch()123456789from transformers import ConvNextV2ForImageClassification
def convnext_v2_base(num_classes): model = ConvNextV2ForImageClassification.from_pretrained( "facebook/convnextv2-base-22k-224", num_labels=num_classes, ignore_mismatched_sizes=True ) return model123version https://git-lfs.github.com/spec/v1oid sha256:837cca126e235c0ae822770470e38a3621b81b0ba7e915aaef2b15a7f66914e6size 3513350851234torchtorchvisiongradioPillow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100105951; Maripa glabra Choisy106023; Merremia umbellata (L.) Hallier f.106387; Costus arabicus L.106461; Costus scaber Ruiz Pav.106466; Costus spiralis (Jacq.) Roscoe110432; Evodianthus funifer (Poit.) Lindm.116853; Pteridium arachnoideum (Kaulf.) Maxon119986; Olfersia cervina (L.) Kunze120497; Diospyros capreifolia Mart. ex Hiern121836; Sloanea grandiflora Sm.121841; Sloanea guianensis (Aubl.) Benth.12254; Anacardium occidentale L.12518; Mangifera indica L.125412; Sphyrospermum cordifolium Benth.126895; Syngonanthus caulescens (Poir.) Ruhland127007; Tonina fluviatilis Aubl.127097; Erythroxylum fimbriatum Peyr.127151; Erythroxylum macrophyllum Cav.127242; Erythroxylum squamatum Sw.12910; Spondias mombin L.12922; Tapirira guianensis Aubl.129645; Croton schiedeanus Schltdl.130657; Euphorbia cotinifolia L.131079; Euphorbia heterophylla L.131736; Euphorbia prostrata Aiton132107; Euphorbia thymifolia L.132113; Euphorbia tithymaloides L.132431; Hura crepitans L.132476; Jatropha curcas L.132501; Jatropha gossypiifolia L.13276; Annona ambotay Aubl.13325; Annona foetida Mart.13330; Annona glabra L.133595; Ricinus communis L.133617; Sapium glandulosum (L.) Morong13370; Annona muricata L.136761; Potalia amara Aubl.138662; Chrysothemis pulchella (Donn ex Sims) Decne.140367; Lembocarpus amoenus Leeuwenb.141068; Sinningia incarnata (Aubl.) D.L.Denham141332; Dicranopteris flexuosa (Schrad.) Underw.141336; Dicranopteris pectinata (Willd.) Underw.142550; Heliconia chartacea Lane ex Barreiros142736; Hernandia guianensis Aubl.143496; Hymenophyllum hirsutum (L.) Sw.14353; Guatteria ouregou (Aubl.) Dunal143706; Trichomanes diversifrons (Bory) Mett. ex Sadeb.143758; Trichomanes punctatum Poir.14401; Guatteria scandens Ducke144394; Didymochlaena truncatula (Sw.) J. Sm.145020; Cipura paludosa Aubl.148220; Aegiphila macrantha Ducke148977; Clerodendrum paniculatum L.149264; Congea tomentosa Roxb.149682; Gmelina philippensis Cham.149919; Holmskioldia sanguinea Retz.150135; Hyptis lanceolata Poir.15014; Rollinia mucosa (Jacq.) Baill.151469; Ocimum campechianum Mill.151593; Orthosiphon aristatus (Blume) Miq.15318; Xylopia aromatica (Lam.) Mart.15330; Xylopia cayennensis Maas15355; Xylopia frutescens Aubl.156516; Aniba guianensis Aubl.156526; Aniba megaphylla Mez158341; Nectandra cissiflora Nees158592; Ocotea cernua (Nees) Mez158653; Ocotea floribunda (Sw.) Mez158736; Ocotea longifolia Kunth158793; Ocotea oblonga (Meisn.) Mez158833; Ocotea puberula (Rich.) Nees159434; Couratari guianensis Aubl.159516; Eschweilera parviflora (Aubl.) Miers159518; Eschweilera pedicellata (Rich.) S.A.Mori160570; Acacia mangium Willd.166822; Caesalpinia pulcherrima (L.) Sw.166869; Cajanus cajan (L.) Millsp.169293; Crotalaria retusa L.171727; Erythrina fusca Lour.173914; Inga alba (Sw.) Willd.173972; Inga capitata Desv.174017; Inga edulis Mart.177730; Mimosa pigra L.177775; Mimosa pudica L.189669; Punica granatum L.191642; Adansonia digitata L.19165; Allamanda cathartica L.192311; Ceiba pentandra (L.) Gaertn.194035; Hibiscus rosa-sinensis L.19489; Asclepias curassavica L.209328; Psidium guineense Sw.211059; Nephrolepis biserrata (Sw.) Schott244705; Averrhoa carambola L.248392; Turnera ulmifolia L.254180; Piper peltatum L.275029; Eichhornia crassipes (Mart.) Solms280085; Ceratopteris thalictroides (L.) Brongn.280698; Pityrogramma calomelanos (L.) Link285398; Cassipourea guianensis Aubl.29686; Oreopanax capitatus (Jacq.) Decne. Planch.app.pyAdded+116
baseline.pyAdded+9
models/herbarium_convnext_v2_base.pthAdded+3
requirements.txtAdded+4
species_list.txtAdded+100