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
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
No comments:
Post a Comment