Friday, 26 April 2024

Machine Learning - Potato Leaf Disease Prediction

Step 1:

import numpy as np
import pandas as pd
import splitfolders
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models, layers

Step 2:

# splitfolders.ratio will create 3 folders named [ train, test, val ]
# ratio = ( .8, .1, .1 )
# move=True will move the image to the respective folder. 

splitfolders.ratio(".", output=".", seed=1337, ratio=(.8, .1,.1,), group_prefix=None, move=False) 

Step 3:

IMAGE_SIZE = 256
CHANNELS = 3

    Part1: 

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
        rescale=1./255,
        rotation_range=10,
        horizontal_flip=True
)
train_generator = train_datagen.flow_from_directory(
        'train',
        target_size=(IMAGE_SIZE,IMAGE_SIZE),
        batch_size=32,
        class_mode="sparse",
)

    Part2:

validation_datagen = ImageDataGenerator(
        rescale=1./255,
        rotation_range=10,
        horizontal_flip=True)
validation_generator = validation_datagen.flow_from_directory(
        'val',
        target_size=(IMAGE_SIZE,IMAGE_SIZE),
        batch_size=32,
        class_mode="sparse"
)

    Part3: 

test_datagen = ImageDataGenerator(
        rescale=1./255,
        rotation_range=10,
        horizontal_flip=True)

test_generator = test_datagen.flow_from_directory(
        'test',
        target_size=(IMAGE_SIZE,IMAGE_SIZE),
        batch_size=32,
        class_mode="sparse"
)

Step 4:

shape = (IMAGE_SIZE, IMAGE_SIZE, CHANNELS)
n_classes = 3
from tensorflow.keras.models import Sequential


model = models.Sequential([   
    layers.Conv2D(32, kernel_size = (3,3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64,  kernel_size = (3,3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64,  kernel_size = (3,3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(n_classes, activation='softmax'),
])

model.compile(
    optimizer='adam',
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
    metrics=['accuracy']
)

Step 5:

from tensorflow.keras.callbacks import TensorBoard
tensorboard_callback = TensorBoard(log_dir='./logs')  # Define a log directory

history = model.fit(
    train_generator,
    batch_size=32,
    validation_data=validation_generator,
    epochs=20,
    callbacks=[tensorboard_callback]
)

Step 6:

model.summary()

Step 7:

model.save('potato.keras')

Tuesday, 16 April 2024

Machine Learning - Dog Cat Prediction using google colab, ngrok, google drive and laravel

Laravel Setup

Routing

Web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;    
 
Route::get('/', function () { return view('welcome'); });
Auth::routes();

Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::post('animals', [HomeController::class, 'animals'])->name('animals');

Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {return redirect('/');})->name('dashboard');


HomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index()
    {
        return view('home');
    }

    public function animals(Request $request)
    {
        $file = $request->file('file');

        // Check if a file was uploaded
        if ($file) {
            $response = Http::attach(
                'file',
                file_get_contents($file->path()),
                $file->getClientOriginalName()
            )->post('https://8c46-34-138-209-204.ngrok-free.app/getanimalscore');
    
            // Handle response from Flask API
            if ($response->successful()) {
                // File uploaded successfully to Flask API
                return $response->json();
            } else {
                // Handle error
                return response()->json(['error' => 'Failed to upload file to Flask API'], $response->status());
            }
        } else {
            return response()->json(['error' => 'No file uploaded'], 400);
        }
    }
     
}

Home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h2>{{ __('Animals') }}</h2>
                </div>

                <div class="card-body">
                    @if (session('status'))
                    <div class="alert alert-success" role="alert">
                        {{ session('status') }}
                    </div>
                    @endif

                    <h4>[Dog - Cat]</h4>
                    <form id="auploadForm" method="POST" enctype="multipart/form-data">
                        @csrf
                        <input type="file" name="file" id="file">
                        <button type="submit">Upload</button>
                    </form>
                    <div id="aresponseContainer"></div>

                </div>
            </div>

        </div>
    </div>
</div>
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    $(document).ready(function () {
        $('#auploadForm').submit(function (e) {
            e.preventDefault(); // Prevent default form submission
            var formData = new FormData($(this)[0]); // Create FormData object  

            // Send AJAX request to Flask API
            $.ajax({
                url: 'http://localhost:8000/animals', // Replace with actual URL
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    // Display response in responseContainer
                    $('#aresponseContainer').html('<p>The image is ' + response['name'] + ' and accuracy is ' + response['score'] + '</p><img src="web/' + formData.get('file').name + '">');
                },
                error: function (xhr, status, error) {
                    // Handle errors
                    $('#aresponseContainer').html('<p>Error: ' + error + '</p>');
                }
            });
        });
    });
</script>
@endsection


$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

 Python

API creation

Api Testing
*****************************
from google.colab import drive
drive.mount('/content/drive')

*****************************
import sys, os
import numpy as np
import tensorflow as tf

from tensorflow.python.keras.models import load_model
from pyngrok import ngrok

from flask import Flask, request, jsonify
from flask_cors import CORS

port_no = 5000
app = Flask(__name__)
ngrok.set_auth_token("2fAmnEsgf1uQEPx45iRCOwTCnoY_6ez8M6fky6JqAr4EfosGL")
public_url =  ngrok.connect(port_no).public_url

CORS(app)  # Enable CORS for all routes

@app.route('/getanimalscore',methods=['POST'])

def getanimalscore():  
      destination_folder = '/content/drive/MyDrive/ML/dogcat-classification/Uploads'

      if 'file' not in request.files:
        return jsonify({'error': 'No file part'})  
     
      file = request.files['file']      
     
      # Check if no file was selected
      if file.filename == '':
         return jsonify({'error': 'No selected file'})      
      file.save(os.path.join(destination_folder, file.filename))
       
      image = os.path.join(destination_folder, file.filename)    
      model = tf.keras.models.load_model('/content/drive/MyDrive/ML/
              dogcat-classification/Dogcat_Classify.keras')
      data_cat = ['Cat','Dog']
      img_height = 254
      img_width = 254
         
      image_load = tf.keras.utils.load_img(image, target_size=(img_height, img_width))
      img_arr = tf.keras.utils.img_to_array(image_load)
      img_bat = np.expand_dims(img_arr, 0)

      predict = model.predict(img_bat)
      score = tf.nn.softmax(predict)
     
      data1 = {
         "name" : data_cat[np.argmax(score)],
         "score" :  str(np.max(score)*100)
      }
      return jsonify(data1 )

print(f"To acces the Gloable link please click {public_url}")
app.run(port=port_no)
 

Model - Training Data

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

data_train_path = 'dogcat_train'
data_val_path = 'dogcat_validation'

img_width = 254
img_height = 254

data_train = tf.keras.utils.image_dataset_from_directory(data_train_path,
    shuffle=True,
    image_size=(img_width, img_height),
    batch_size=16,
    validation_split=False)

data_val = tf.keras.utils.image_dataset_from_directory(data_val_path,
       shuffle=False,
       image_size=(img_height,img_width),
       batch_size=16,       
       validation_split=False)

from tensorflow.keras.models import Sequential

#Data Training
model = Sequential([
    layers.Rescaling(1./255),
    layers.Conv2D(16, 3, padding='same', activation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(32,3, padding='same',activation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(64, 3, padding='same', activation='relu'),
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dropout(0.2),
    layers.Dense(128),
    layers.Dense(len(data_cat))                  
])

model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

#If you want to see on tensorboard
from tensorflow.keras.callbacks import TensorBoard
tensorboard_callback = TensorBoard(log_dir='./logs')  # Define a log directory

epochs_size = 15
history = model.fit(data_train, validation_data=data_val, epochs=epochs_size, callbacks=[tensorboard_callback])
 
model.save('Dogcat_Classify.keras')

#Testing the model with 1 data
image = 'img1.jpg'
image = tf.keras.utils.load_img(image, target_size=(img_height,img_width))
img_arr = tf.keras.utils.array_to_img(image)
img_bat = tf.expand_dims(img_arr,0)
predict = model.predict(img_bat)
score = tf.nn.softmax(predict)
print('{} with accuracy of {:0.2f}'.format(data_cat[np.argmax(score)],np.max(score)*100))


#ngrok

 

Googledrive

 

 

 

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...