Commit a7279821 authored by chalaka78's avatar chalaka78

next service date BE

parent ef3abe04
......@@ -60,3 +60,18 @@ class MyForm3(forms.Form):
#Customer Frequency
class MyForm(forms.Form):
customerid = forms.IntegerField(label='Customer ID', widget=forms.TextInput(attrs={'class': 'input_field', 'required': True}))
#Maitenance Date
MODE_SERVICES = [
('0', 'Select Service Type'),
('1', 'Full Service')
]
class MyFormServices(forms.Form):
customerid = forms.IntegerField(label='Enter Customer ID ')
Vnumber = forms.CharField(label='Enter Vehicle Number ')
ServiceType = forms.IntegerField(label="Select Service", widget=forms.Select(choices=MODE_SERVICES))
......@@ -18,5 +18,7 @@ urlpatterns = [
path('Result/', responseapp_views.Forecasting),
path('Customer_Data/', responseapp_views.Customer_Data),
path('Customer_Frequency/', responseapp_views.Customer_Frequency),
path('MaintainData/', responseapp_views.MaintainData),
path('NextMaintain/', responseapp_views.NextMaintain),
path('', admin.site.urls),
]
\ No newline at end of file
......@@ -4,8 +4,9 @@ from django.template import loader
from django.http import HttpResponse
from sklearn.tree import DecisionTreeClassifier
from User.forms import MyForm,MyForm2,MyForm3,MyForm4,MyForm5
from User.forms import MyForm,MyForm2,MyForm3,MyForm4,MyForm5,MyFormServices
from django.contrib.auth import authenticate, login
from sklearn.linear_model import LogisticRegression
from User import models as Umodels
from django.http import HttpResponseRedirect
from django.contrib import messages
......@@ -274,22 +275,6 @@ def Forecasting(request):
# End Demand Forecasting Machine Learning Model
def AdminLogin(request):
if request.method == 'POST':
myForm = MyForm2(request.POST)
if myForm.is_valid():
UserName = myForm.cleaned_data['UserName']
Password = myForm.cleaned_data['Password']
gotdata = Umodels.loginDataAdmin.objects.all().filter(UserName=UserName , Password=Password).count()
if gotdata > 0:
return render(request, 'Admin/AdminHome.html');
else:
messages.success(request, 'Login Info Not Found , Please Check Your UserName and Password')
return HttpResponseRedirect(request.path_info)
else:
form = MyForm2()
return render(request, 'Admin/AdminLogin.html', {'form':form});
# Customer Data
def Customer_Data(request):
data = pd.read_csv('Data/CustomerDatasetNew_4.csv')
......@@ -426,8 +411,6 @@ def Customer_Frequency(request):
form = MyForm()
return render(request, 'Admin/Customer_Frequency.html', {'form': form});
def AdminHome(request):
return render(request,'Admin/AdminHome.html')
# tensorflow sound detection model
# import tensorflow as tf
......@@ -487,6 +470,239 @@ def AdminHome(request):
# model.save('./model.h5')
#Next Maintain Date
def NextMaintain(request):
if request.method == 'POST':
myForm = MyFormServices(request.POST)
#myForm3 = MyForm3(request.POST or None)
# price prediction with logitic
if myForm.is_valid():
customerid = myForm.cleaned_data['customerid']
checkValid = pd.read_csv('Data/MaintainData.csv')
checkValid = checkValid[(checkValid["Customer"] == customerid)]
print("Validation----------------------")
checkValid = (checkValid.shape[0])
if (checkValid > 0):
ServiceType = myForm.cleaned_data['ServiceType']
customerid = myForm.cleaned_data['customerid']
Vnumber = myForm.cleaned_data['Vnumber']
df = pd.read_csv('Data/MaintainData.csv')
df = df[(df["Customer"] == customerid)]
df = df[(df["Service"] == ServiceType)]
df = df[(df["VehicleNumber"] == Vnumber)]
df.shape
dataset = df.head()
# print(dataset)
# do same but attach it to the dataframe
# df['Different'] = df.apply(lambda row: 45, axis=1)
df['a'] = pd.to_datetime(df['Date']).diff()
df['a'] = df['a'].astype(str).str.replace("days", "")
df['a'] = df['a'].astype(str).str.replace("NaT", "30")
print(df)
X = df[['TakenTime', 'Price', 'MeterReading']]
y = df['a']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
Accuracy = logreg.score(X_test, y_test)
print(Accuracy)
MeterReading = df['MeterReading'].mean()
# print(MeterReading)
new_input = [[28, 200, MeterReading]]
pred = logreg.predict(new_input)
pred = int(pred)
print("--------------Customer will come after days---------------------")
# print(pred)
startdate = "7/7/2021"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=pred)
print(enddate)
df = df[:1]
# data = data.to_html()
json_records = df.reset_index().to_json(orient='records')
arr = []
arr = json.loads(json_records)
if (arr == [] ):
# data = data.to_html()
json_records = df.reset_index().to_json(orient='records')
arr = []
arr = json.loads(json_records)
else:
a = 2
form = MyFormServices()
enddate = enddate.strftime("%d/%m/%Y")
# parts = enddate.split(' ')
# message_count = int(parts[0])
# print(message_count)
# ARIMA SECTION
# inputdate = '12/01/2020'
# HERE I USE AN EXMAMPLE FROM MATPLOTLIB SITE
# Data for plotting
# t = np.arange(0.0, 2.0, 0.01)
# s = 1 + np.sin(2 * np.pi * t)
import numpy as np
import matplotlib.pyplot as plt
df2 = pd.read_csv('Data/MaintainData.csv')
df2 = df2[(df2["Customer"] == customerid)]
df2 = df2[(df2["Service"] == ServiceType)]
df = df2[(df2["VehicleNumber"] == Vnumber)]
#df.drop('Service','ServiceName','TakenTime','Customer','VehicleType','VehicleMake','VehicleModel','VehicleNumber','MeterReading','VehicleManufacturedYear','AvergeUsage','mailID', axis=1, inplace=True)
df = df.drop(columns=['Service','ServiceName','TakenTime','Customer','VehicleType','VehicleMake','VehicleModel','VehicleNumber','MeterReading','VehicleManufacturedYear','AvergeUsage','mailID', ])
df.head()
## Cleaning up the data
df.columns = ["Date", "Price"]
rrr = df.head()
## Drop last 2 rows
#df.drop(106, axis=0, inplace=True)
#df.tail()
# df.drop(105, axis=0, inplace=True)
# df.tail()
# Convert Date into Datetime
df['Date'] = pd.to_datetime(df['Date'])
df.head()
df.set_index('Date', inplace=True)
df.head()
df.describe()
# df.plot()
# plt.show()
### Testing For Stationarity
from statsmodels.tsa.stattools import adfuller
test_result = adfuller(df['Price'])
def adfuller_test(Price):
result = adfuller(Price)
labels = ['ADF Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']
for value, label in zip(result, labels):
print(label + ' : ' + str(value))
if result[1] <= 0.05:
print(
"strong evidence against the null hypothesis(Ho), reject the null hypothesis. Data has no unit root and is stationary")
else:
print(
"weak evidence against null hypothesis, time series has a unit root, indicating it is non-stationary ")
adfuller_test(df['Price'])
##Differencing
df['Price First Difference'] = df['Price'] - df['Price'].shift(1)
df['Price'].shift(1)
df['Seasonal First Difference'] = df['Price'] - df['Price'].shift(12)
# df.head(14)
## Again test dickey fuller test
adfuller_test(df['Seasonal First Difference'].dropna())
import statsmodels.api as sm
# For non-seasonal data
# p=1, d=1, q=0 or 1
# from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(df['Price'], order=(1, 1, 1))
model_fit = model.fit()
# model_fit.summary()
# df['forecast'] = model_fit.predict(start=8, end=8, dynamic=True)
# df[['Price','forecast']].plot(figsize=(12,8))
model = sm.tsa.statespace.SARIMAX(df['Price'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
results = model.fit()
from pandas.tseries.offsets import DateOffset
future_dates = [df.index[-1] + DateOffset(months=x) for x in range(0, 150)]
future_datest_df = pd.DataFrame(index=future_dates[1:], columns=df.columns)
# future_datest_df.tail()
future_df = pd.concat([df, future_datest_df])
print(future_df)
Datefinding = int(df.shape[1] + 15)
print(Datefinding)
forecastedPrice = future_df['forecast'] = results.predict(start=Datefinding, end=Datefinding, dynamic=True)
print("its Arima output")
forecastedPrice = (forecastedPrice.to_string())
print(forecastedPrice[5:13])
else:
form = MyFormServices()
context = {'form': form,'d': "CUSTOMER NOT FOUND"}
return render(request, 'Admin/NextMaintain.html', context)
context = { 'form': form, 'd': enddate , 'forecastedPrice':' Rs ' + forecastedPrice[5:13] }
return render(request, 'Admin/NextMaintain.html', context)
else:
form = MyFormServices()
return render(request, 'Admin/NextMaintain.html', {'form': form });
def MaintainData(request):
data1 = pd.read_csv('Data/MaintainData.csv')
finalpt = data1.head(10)
json_records = finalpt.reset_index().to_json(orient='records')
arr = []
arr = json.loads(json_records)
context = {'d': arr}
return render(request, 'Admin/MaintainData.html',context);
def AdminLogin(request):
if request.method == 'POST':
myForm = MyForm2(request.POST)
if myForm.is_valid():
UserName = myForm.cleaned_data['UserName']
Password = myForm.cleaned_data['Password']
gotdata = Umodels.loginDataAdmin.objects.all().filter(UserName=UserName , Password=Password).count()
if gotdata > 0:
return render(request, 'Admin/AdminHome.html');
else:
messages.success(request, 'Login Info Not Found , Please Check Your UserName and Password')
return HttpResponseRedirect(request.path_info)
else:
form = MyForm2()
return render(request, 'Admin/AdminLogin.html', {'form':form});
def AdminHome(request):
return render(request,'Admin/AdminHome.html')
......
No preview for this file type
{% extends 'Admin/Sidebar2.html' %}
{% block content %}
{% load widget_tweaks %}
{%load static%}
<head>
<!-- Font special for pages-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
<!-- Main CSS-->
<link href="{% static "css/main.css" %}"rel="stylesheet" media="all">
</head>
<div class=" >
<div class="wrapper wrapper 0">
<div style="margin-left: 0px;" class="card card-5">
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li>
{% endfor %}
</ul>
{% endif %}
<div class="card-heading">
<h2 class="title"> MAINTAINS DATA </h2>
</div>
<div id="myDiv">
<div id="div_print">
<div class="card card-body printableArea">
<div class="container" style="overflow-x:auto;">
Customer Maintains Data
<table class="table table-striped">
<thead>
<tr>
<th> Service Date </th>
<th> Service </th>
<th> Taken Time </th>
<th> Price </th>
<th> Customer </th>
<th> Vehicle Type </th>
<th> Vehicle Make </th>
<th> Vehicle Model </th>
<th> Vehicle Number </th>
<th> Meter Reading </th>
<th> Vehicle Manufactured Year </th>
<th> Average Usage </th>
</tr>
</thead>
<tbody>
{% if d %}
{% for i in d %}
<tr>
<td>{{i.Date}}</td>
<td>{{i.ServiceName}}</td>
<td>{{i.TakenTime}}</td>
<td>{{i.Price}}</td>
<td>{{i.Customer}}</td>
<td>{{i.VehicleType}} </td>
<td>{{i.VehicleMake}} </td>
<td>{{i.VehicleModel}} </td>
<td>{{i.VehicleNumber}} </td>
<td>{{i.MeterReading}} </td>
<td>{{i.VehicleManufacturedYear}} </td>
<td>{{i.AverageUsage}} </td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</div>
</div>
</div></div>
<script language="javascript">
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
window.print();
document.body.innerHTML = oldstr;
location.reload();
return false;
}
</script>
<div class="card-body">
<input name="b_print" type="button" class="btn btn-primary btn-print" onClick="printdiv('div_print');" value=" Print ">
</div>
<div class="alert alert-primary" role="alert" >© SMART SERVICE STATION 2022 </div>
</div>
</div>
</div>
</div>
{% endblock content %}
......@@ -15,14 +15,12 @@
<div style="margin-left: 0px;" class="card card-5">
<br/><br/>
{% if messages %}
<div class="alert alert-danger" role="alert">
<ul class="messages">
{% for message in messages %}
{% if message.tags %} {% endif %} {{ message }}
<li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li>
{% endfor %}
</div>
</ul>
{% endif %}
<div class="card-heading">
......@@ -31,37 +29,50 @@
<div class="card-body">
<form action="/Admin/Predicted_Date/" method="post">
<form action="/Admin/NextMaintain/" method="post">
{% csrf_token %}
<table class="table table-light">
{{form3.as_table}}
{{form.as_table}}
</table>
<input type="submit" value="NEXT MAINTAIN DATE" class="btn btn--radius-2 btn" style="background:#02111f"/>
<input type="submit" value="NEXT MAINTAIN DATE" class="btn btn--radius-2 btn-primary"/>
<div role="alert">
<center><h3> {{ d }} </h3></center>
</div>
</form>
<br>
<center> <div class="alert alert-success">
{{ d }}
{{ forecastedPrice }}
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
</div> </center>
</div>
</div>
</div><div class="alert alert-primary fixed-bottom mb-0 text-center" style="background: #747578; border: none; color: white;" role="alert" > © SERVPORT 2022 </div>
</div>
<div class="alert alert-primary" role="alert" >© SMART SERVICE STATION 2022 </div>
</div>
{% endblock content %}
{% extends 'Admin/Sidebar2.html' %}
{% block content %}
{% load widget_tweaks %}
{%load static%}
<head>
<!-- Font special for pages-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
<!-- Main CSS-->
<link href="{% static "css/main.css" %}"rel="stylesheet" media="all">
</head>
<center>
<div class=">
<div class="wrapper wrapper--w790">
<div style="margin-left: 0px;" class="card card-5">
<div class="card-heading">
<h2 class="title"> Next Service Date </h2>
</div>
{% autoescape off %}
<div>{{ g }}</div>
{% endautoescape %}
<div class="alert alert-danger" role="alert">
Next Service Date is : {{ d }}
<br>
</div>
</div>
</div>
</div>
{% endblock content %}
......@@ -188,8 +188,8 @@ body{
<li><a style="text-decoration:none;" href="/Admin/PurchaseHistory/"><i class="fas fa-cubes"></i> Purchase History </a>
<li><a style="text-decoration:none;" href="/Admin/Customer_Data/"><i class="fas fa-user"></i> Customer Data </a>
<li><a style="text-decoration:none;" href="/Admin/Customer_Frequency/"><i class="fas fa-chart-bar"></i> Customer Frequency </a>
<li><a style="text-decoration:none;" href="/Admin/Next_Maintain/"><i class="fas fa-user"></i> Next Service Date </a>
<li><a style="text-decoration:none;" href="/Admin"><i class="fas fa-chart-bar"></i> Vehicle Maintenance Data </a>
<li><a style="text-decoration:none;" href="/Admin/NextMaintain/"><i class="fas fa-user"></i> Next Service Date </a>
<li><a style="text-decoration:none;" href="/Admin/MaintainData/"><i class="fas fa-chart-bar"></i> Maintenance Data </a>
</ul>
</div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment