yolac commited on
Commit
d9f1830
·
verified ·
1 Parent(s): eae2c3c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -36
app.py CHANGED
@@ -1,39 +1,67 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
  import requests
4
- import tempfile
5
-
6
- # Define the URL for your model and dataset
7
- model_url = 'https://huggingface.co/yolac/BacterialMorphologyClassification/resolve/main/bacterial_morphology_classification_model.h5'
8
-
9
- # Download the model from the URL and load it into a temporary file
10
- response = requests.get(model_url, stream=True)
11
- if response.status_code == 200:
12
- with tempfile.NamedTemporaryFile(delete=False, suffix='.h5') as temp_file:
13
- temp_file.write(response.content)
14
- temp_file_path = temp_file.name
15
- model = tf.keras.models.load_model(temp_file_path)
16
- else:
17
- raise Exception(f"Failed to download the model. Status code: {response.status_code}")
18
-
19
- # Define the function for prediction
20
- def predict_image(img):
21
- img = img.resize((224, 224))
22
- img_array = tf.keras.preprocessing.image.img_to_array(img) / 255.0
23
- img_array = tf.expand_dims(img_array, axis=0)
24
- prediction = model.predict(img_array)
25
- classes = ['cocci', 'bacilli', 'spirilla']
26
- predicted_class = classes[prediction.argmax()]
27
- return predicted_class
28
-
29
- # Create the Gradio interface
30
- iface = gr.Interface(
31
- fn=predict_image,
32
- inputs=gr.inputs.Image(shape=(224, 224)),
33
- outputs=gr.outputs.Label(num_top_classes=3),
34
- title="Bacterial Morphology Classification",
35
- description="Upload an image of bacterial morphology to classify it as cocci, bacilli, or spirilla."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  )
37
 
38
- # Launch the Gradio app
39
- iface.launch()
 
 
 
 
 
1
+ import os
 
2
  import requests
3
+ from datasets import load_dataset
4
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
5
+ import torch
6
+
7
+ # Step 1: Set up environment and check paths
8
+ MODEL_PATH = "yolac/BacterialMorphologyClassification"
9
+ DATASET_PATH = "yolac/BacterialMorphologyClassification"
10
+
11
+ # Step 2: Load the model
12
+ try:
13
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH, num_labels=3)
14
+ print("Model loaded successfully.")
15
+ except Exception as e:
16
+ print(f"Failed to load the model. Error: {e}")
17
+
18
+ # Step 3: Load the tokenizer (if needed)
19
+ try:
20
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
21
+ print("Tokenizer loaded successfully.")
22
+ except Exception as e:
23
+ print(f"Failed to load the tokenizer. Error: {e}")
24
+
25
+ # Step 4: Load the dataset
26
+ try:
27
+ dataset = load_dataset(DATASET_PATH, split="train")
28
+ print("Dataset loaded successfully.")
29
+ except Exception as e:
30
+ print(f"Failed to load the dataset. Error: {e}")
31
+
32
+ # Step 5: Preprocess and prepare data for model input (example code)
33
+ def preprocess_data(example):
34
+ # Add any necessary preprocessing steps here, e.g., tokenization
35
+ return tokenizer(example['text'], padding="max_length", truncation=True)
36
+
37
+ # Apply preprocessing
38
+ dataset = dataset.map(preprocess_data, batched=True)
39
+
40
+ # Step 6: Set up training arguments (use the `Trainer` class if needed)
41
+ from transformers import Trainer, TrainingArguments
42
+
43
+ training_args = TrainingArguments(
44
+ output_dir="./results",
45
+ evaluation_strategy="epoch",
46
+ learning_rate=2e-5,
47
+ per_device_train_batch_size=8,
48
+ per_device_eval_batch_size=8,
49
+ num_train_epochs=3,
50
+ weight_decay=0.01,
51
+ logging_dir="./logs",
52
+ )
53
+
54
+ # Initialize the Trainer
55
+ trainer = Trainer(
56
+ model=model,
57
+ args=training_args,
58
+ train_dataset=dataset,
59
+ tokenizer=tokenizer,
60
  )
61
 
62
+ # Step 7: Train the model
63
+ try:
64
+ trainer.train()
65
+ print("Training completed successfully.")
66
+ except Exception as e:
67
+ print(f"Failed to train the model. Error: {e}")