├── .gitattributes ├── Chapter10 ├── model │ ├── .ipynb_checkpoints │ │ ├── JSONtoCSV-checkpoint.ipynb │ │ ├── LSTM Model-checkpoint.ipynb │ │ ├── Security NN-checkpoint.ipynb │ │ └── Security-with-LSTM-checkpoint.ipynb │ ├── LSTM Model.ipynb │ ├── app.py │ ├── data │ │ ├── data-full.csv │ │ └── data.csv │ ├── lstm-model.h5 │ └── lstm-weights.h5 └── webapp │ ├── billboard │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── forms.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-37.pyc │ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── templates │ │ ├── add.html │ │ ├── base.html │ │ ├── board.html │ │ └── login.html │ ├── tests.py │ ├── urls.py │ └── views.py │ ├── db.sqlite3 │ ├── manage.py │ └── webapp │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── settings.cpython-37.pyc │ ├── urls.cpython-37.pyc │ └── wsgi.cpython-37.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Chapter11 ├── app │ ├── Procfile │ ├── app.py │ ├── requirements.txt │ └── templates │ │ └── index.html ├── data │ └── heart.csv └── model │ ├── .ipynb_checkpoints │ └── PartialFit-checkpoint.ipynb │ └── PartialFit.ipynb ├── Chapter12 ├── ecomsite │ ├── db.sqlite3 │ ├── ecomsite │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── settings.cpython-37.pyc │ │ │ ├── urls.cpython-37.pyc │ │ │ └── wsgi.cpython-37.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── orders │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── forms.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms.py │ │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20191205_1259.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-37.pyc │ │ │ ├── 0002_auto_20191205_1259.cpython-37.pyc │ │ │ └── __init__.cpython-37.pyc │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py └── ordersui │ ├── Procfile │ ├── apiui │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── templates │ │ ├── base.html │ │ ├── index.html │ │ └── view.html │ ├── tests.py │ ├── urls.py │ └── views.py │ ├── manage.py │ ├── ordersui │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── wsgi.cpython-37.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ └── requirements.txt ├── Chapter3 ├── app │ ├── LICENSE │ ├── flask_app.py │ ├── flask_both.py │ ├── flask_cli.py │ ├── model.json │ ├── static │ │ ├── index.js │ │ └── style.css │ ├── templates │ │ └── index.html │ └── weights.h5 └── model │ ├── .ipynb_checkpoints │ └── mnist-keras-checkpoint.ipynb │ └── mnist-keras.ipynb ├── Chapter4 ├── .gitignore ├── README.md ├── index.js ├── iris.json ├── package-lock.json ├── package.json └── public │ └── index.html ├── Chapter6 ├── CloudVisionClientExample │ ├── .ipynb_checkpoints │ │ └── CloudVisionAPIExample-checkpoint.ipynb │ ├── CloudVisionAPIExample.ipynb │ └── test.jpg ├── DialogFlow_Python_API_Example │ ├── .ipynb_checkpoints │ │ ├── DialogFlowTestIntent-checkpoint.ipynb │ │ └── Untitled-checkpoint.ipynb │ └── DialogFlowTestIntent.ipynb └── GoogleCloudTranslateExample │ ├── .ipynb_checkpoints │ └── CloudTranslateAPIExample-checkpoint.ipynb │ └── CloudTranslateAPIExample.ipynb ├── Chapter7 ├── AlexaSkillExample │ └── lambda_function.py ├── Boto3 Setup.ipynb ├── RekognitionExample │ ├── .ipynb_checkpoints │ │ └── Sample-checkpoint.ipynb │ ├── Sample.ipynb │ └── image.jpg └── my_image.jpeg ├── Chapter8 ├── CNTKDemo │ ├── api │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── admin.cpython-37.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── models.cpython-37.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ ├── urls.cpython-37.pyc │ │ │ ├── views.cpython-36.pyc │ │ │ └── views.cpython-37.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ └── __init__.cpython-37.pyc │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── cntkdemo │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── settings.cpython-36.pyc │ │ │ ├── settings.cpython-37.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ ├── urls.cpython-37.pyc │ │ │ ├── wsgi.cpython-36.pyc │ │ │ └── wsgi.cpython-37.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── data │ │ └── myModel.model │ ├── db.sqlite3 │ ├── manage.py │ ├── static │ │ ├── index.js │ │ └── style.css │ └── templates │ │ └── api │ │ └── index.html ├── Face API │ └── Face API in Python.ipynb ├── Text Analytics API │ └── Text Analytics API.ipynb └── sample_image.jpg ├── Chapter9 ├── .ipynb_checkpoints │ ├── Recommendations-checkpoint.ipynb │ ├── Untitled-checkpoint.ipynb │ └── recommendation-checkpoint.ipynb ├── Recommendations.ipynb └── api │ ├── .DS_Store │ ├── main.py │ ├── model.pkl │ ├── static │ └── bootstrap.min.css │ └── templates │ └── index.html ├── Code for generating plots └── plotting.py ├── Excel ├── Convolutions.xlsx ├── RNNs.xlsx └── Toy Dataset.xlsx ├── LICENSE ├── README.md ├── XMLs for figures ├── Big Picture of AI, ML and DL.xml ├── Convolution.xml ├── NeuralNetworkAnatomy (2).xml ├── Overfitting and underfitting.xml ├── RNN Unrolled (1).xml └── training-error-gen-error.xml └── _config.yml /.gitattributes: -------------------------------------------------------------------------------- 1 | Reviews.csv filter=lfs diff=lfs merge=lfs -text 2 | Chapter9/Reviews.csv filter=lfs diff=lfs merge=lfs -text 3 | -------------------------------------------------------------------------------- /Chapter10/model/.ipynb_checkpoints/Security NN-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 2 6 | } 7 | -------------------------------------------------------------------------------- /Chapter10/model/.ipynb_checkpoints/Security-with-LSTM-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 2 6 | } 7 | -------------------------------------------------------------------------------- /Chapter10/model/app.py: -------------------------------------------------------------------------------- 1 | from sklearn.externals import joblib 2 | from flask import Flask, request, jsonify 3 | from string import digits 4 | 5 | import sys 6 | import os 7 | import json 8 | import pandas 9 | import numpy 10 | import optparse 11 | from keras.models import Sequential, load_model 12 | from keras.preprocessing import sequence 13 | from keras.preprocessing.text import Tokenizer 14 | from collections import OrderedDict 15 | 16 | app = Flask(__name__) 17 | 18 | model = load_model('lstm-model.h5') 19 | model.load_weights('lstm-weights.h5') 20 | model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) 21 | model._make_predict_function() 22 | 23 | def remove_digits(s: str) -> str: 24 | remove_digits = str.maketrans('', '', digits) 25 | res = s.translate(remove_digits) 26 | return res 27 | 28 | @app.route('/login', methods=['GET', 'POST']) 29 | def login(): 30 | req = dict(request.headers) 31 | item = {} 32 | item["method"] = str(request.method) 33 | item["query"] = str(request.query_string) 34 | item["path"] = str(request.path) 35 | item["statusCode"] = 200 36 | item["requestPayload"] = [] 37 | 38 | X = numpy.array([json.dumps(item)]) 39 | log_entry = "store" 40 | 41 | tokenizer = Tokenizer(filters='\t\n', char_level=True) 42 | tokenizer.fit_on_texts(X) 43 | seq = tokenizer.texts_to_sequences([log_entry]) 44 | max_log_length = 1024 45 | log_entry_processed = sequence.pad_sequences(seq, maxlen=max_log_length) 46 | 47 | prediction = model.predict(log_entry_processed) 48 | print(prediction) 49 | response = {'result': float(prediction[0][0])} 50 | return jsonify(response) 51 | 52 | if __name__ == '__main__': 53 | app.run(port=9000, debug=True) -------------------------------------------------------------------------------- /Chapter10/model/lstm-model.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/model/lstm-model.h5 -------------------------------------------------------------------------------- /Chapter10/model/lstm-weights.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/model/lstm-weights.h5 -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__init__.py -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__pycache__/admin.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__pycache__/admin.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__pycache__/forms.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__pycache__/forms.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__pycache__/models.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__pycache__/models.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/__pycache__/views.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/__pycache__/views.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class BillboardConfig(AppConfig): 5 | name = 'billboard' 6 | -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.0.8 on 2019-09-06 14:10 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.utils.timezone 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Bills', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('billName', models.CharField(default='New Bill', max_length=100, verbose_name='Bill Name')), 22 | ('billDesc', models.TextField()), 23 | ('billTime', models.DateTimeField(default=django.utils.timezone.now, editable=False)), 24 | ('user', models.ForeignKey(on_delete='CASCADE', to=settings.AUTH_USER_MODEL)), 25 | ], 26 | options={ 27 | 'db_table': 'bills', 28 | }, 29 | ), 30 | ] 31 | -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/migrations/__init__.py -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/migrations/__pycache__/0001_initial.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/migrations/__pycache__/0001_initial.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/migrations/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/billboard/migrations/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | from django.utils.timezone import now 4 | from django.contrib.auth.models import User 5 | 6 | # Create your models here. 7 | class Bills(models.Model): 8 | billName = models.CharField("Bill Name", blank=False, max_length=100, default="New Bill") 9 | user = models.ForeignKey(User, on_delete="CASCADE") 10 | billDesc = models.TextField("Bill Description") 11 | billTime = models.DateTimeField(default=now, editable=False) 12 | 13 | class Meta: 14 | db_table = "bills" -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/templates/add.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% block content %} 3 |
4 |
5 |
6 |
7 | {% csrf_token %} 8 |

Add Bill

9 |
10 |
11 | 12 |
13 |
14 | 15 |
16 |
17 |
18 | 19 |
20 |
21 |
22 |
23 |
24 | 25 | 33 | {% endblock %} -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | BillBoard Test App 11 | 12 | 35 | 36 | 37 | 38 | 54 |
55 |
56 |
57 |
58 | {% block content %} 59 | {% endblock %} 60 |
61 |
62 |
63 |
64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/templates/board.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% block content %} 3 |
4 |
5 | {% for bill in bills %} 6 |
7 |
8 |

{{ bill.billName }}

9 |
10 |

11 | {{ bill.billDesc }} 12 |

13 | {{ bill.user.username }} 14 |
15 |
16 | {% endfor %} 17 |
18 |
19 | {% endblock %} -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/templates/login.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% block content %} 3 |
4 |
5 |
6 |
7 | {% csrf_token %} 8 |

Login Page

9 |
10 |
11 | 12 |
13 |
14 | 15 |
16 |
17 |
18 | 19 |
20 |
21 |
22 |
23 |
24 | {% endblock %} -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from django.contrib.auth.decorators import login_required 3 | 4 | from . import views 5 | 6 | urlpatterns = [ 7 | path('', login_required(views.board), name='View Board'), 8 | path('add', login_required(views.addbill), name='Add Bill'), 9 | path('login', views.loginView, name='Login'), 10 | path('logout', views.logoutView, name='Logout'), 11 | ] -------------------------------------------------------------------------------- /Chapter10/webapp/billboard/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, render_to_response 2 | from django.http import HttpResponse 3 | from django.template import loader 4 | 5 | import datetime 6 | 7 | from django.shortcuts import redirect 8 | from django.contrib.auth import authenticate, login, logout 9 | 10 | from django.conf import settings 11 | from django.urls import reverse_lazy 12 | from django.views import generic 13 | 14 | from django.contrib.auth.models import User 15 | from .models import Bills 16 | 17 | from django.conf import settings 18 | 19 | import urllib 20 | import ssl 21 | import json 22 | 23 | def board(request): 24 | template = loader.get_template('board.html') 25 | context = {} 26 | context["isLogged"] = 1 27 | 28 | Bill = Bills.objects.all() 29 | 30 | context["bills"] = Bill 31 | 32 | return HttpResponse(template.render(context, request)) 33 | 34 | def addbill(request): 35 | print(request.POST) 36 | 37 | if request.POST: 38 | recaptcha_response = request.POST.get('g-recaptcha-response') 39 | url = 'https://www.google.com/recaptcha/api/siteverify' 40 | values = { 41 | 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 42 | 'response': recaptcha_response 43 | } 44 | 45 | # This restores the same behavior as before. 46 | context = ssl._create_unverified_context() 47 | data = urllib.parse.urlencode(values).encode() 48 | req = urllib.request.Request(url, data=data) 49 | response = urllib.request.urlopen(req, context=context) 50 | result = json.loads(response.read().decode()) 51 | 52 | if result['success']: 53 | billName = request.POST['billname'] 54 | billDesc = request.POST['billdesc'] 55 | Bill = Bills.objects.create(billName=billName, user=request.user, billDesc=billDesc) 56 | Bill.save() 57 | return redirect('/') 58 | else: 59 | print(result) 60 | return redirect('/add') 61 | else: 62 | template = loader.get_template('add.html') 63 | context = {} 64 | context["isLogged"] = 1 65 | 66 | return HttpResponse(template.render(context, request)) 67 | 68 | def loginView(request): 69 | if request.user.is_authenticated: 70 | return redirect('/') 71 | else: 72 | if request.POST: 73 | username = request.POST['username'] 74 | password = request.POST['password'] 75 | user = authenticate(request, username=username, password=password) 76 | if user is not None: 77 | url = 'http://127.0.0.1:9000/login' 78 | values = { 79 | 'username': username, 80 | 'password': password 81 | } 82 | data = urllib.parse.urlencode(values).encode() 83 | req = urllib.request.Request(url, data=data) 84 | response = urllib.request.urlopen(req) 85 | result = json.loads(response.read().decode()) 86 | print(result) 87 | if result['result'] > 0.20: 88 | login(request, user) 89 | return redirect('/') 90 | else: 91 | return redirect('/logout') 92 | else: 93 | return redirect('/logout') 94 | else: 95 | template = loader.get_template('login.html') 96 | context = {} 97 | return HttpResponse(template.render(context, request)) 98 | 99 | 100 | def logoutView(request): 101 | logout(request) 102 | return redirect('/') -------------------------------------------------------------------------------- /Chapter10/webapp/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/db.sqlite3 -------------------------------------------------------------------------------- /Chapter10/webapp/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapp.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/webapp/__init__.py -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/webapp/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/__pycache__/settings.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/webapp/__pycache__/settings.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/webapp/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/__pycache__/wsgi.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter10/webapp/webapp/__pycache__/wsgi.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for webapp project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.0.8. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '_lx#_t9(3k-&k%=$g$tfj_k-xht9i215&sc37ahvvma+9#h*f$' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'billboard', 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'webapp.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'webapp.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/2.0/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/2.0/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | 123 | STATICFILES_DIRS = [ 124 | os.path.join(BASE_DIR, "static") 125 | ] 126 | 127 | LOGIN_URL = "/login" 128 | LOGIN_REDIRECT_URL = '/' 129 | LOGOUT_REDIRECT_URL = '/logout' 130 | 131 | GOOGLE_RECAPTCHA_SECRET_KEY = '6Lfi6ncUAAAAANJYkMC66skocDgA1REblmx0-3B2' -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/urls.py: -------------------------------------------------------------------------------- 1 | """webapp URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('', include('billboard.urls')), 21 | path('admin/', admin.site.urls), 22 | ] 23 | -------------------------------------------------------------------------------- /Chapter10/webapp/webapp/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for webapp project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapp.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Chapter11/app/Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn app:app -------------------------------------------------------------------------------- /Chapter11/app/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify, render_template 2 | 3 | import pandas as pd 4 | import numpy as np 5 | from sklearn.model_selection import train_test_split 6 | from sklearn.preprocessing import StandardScaler 7 | from sklearn.neural_network import MLPClassifier 8 | 9 | np.random.seed(5) 10 | 11 | df = pd.read_csv("https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/master/Chapter11/data/heart.csv") 12 | 13 | X = df.drop("target",axis=1) 14 | y = df["target"] 15 | 16 | X = StandardScaler().fit_transform(X) 17 | X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.20,random_state=0) 18 | 19 | clf = MLPClassifier(max_iter=200) 20 | 21 | for i in range(100): 22 | xt = X_train[i].reshape(1, -1) 23 | yt = y_train.values[[i]] 24 | clf = clf.partial_fit(xt, yt, classes=[0,1]) 25 | if i > 0 and i % 25 == 0 or i == len(X_train) - 1: 26 | score = clf.score(X_test, y_test) 27 | print("Iters ", i, ": ", score) 28 | 29 | score = clf.score(X_test, y_test) 30 | 31 | app = Flask(__name__) 32 | 33 | start_at = 100 34 | 35 | @app.route('/train_batch', methods=['GET', 'POST']) 36 | def train_batch(): 37 | global start_at, clf, X_train, y_train, X_test, y_test, score 38 | for i in range(start_at, min(start_at+25, len(X_train))): 39 | xt = X_train[i].reshape(1, -1) 40 | yt = y_train.values[[i]] 41 | clf = clf.partial_fit(xt, yt, classes=[0,1]) 42 | 43 | score = clf.score(X_test, y_test) 44 | 45 | start_at += 25 46 | 47 | response = {'result': float(round(score, 5)), 'remaining': len(X_train) - start_at} 48 | 49 | return jsonify(response) 50 | 51 | @app.route('/reset', methods=['GET', 'POST']) 52 | def reset(): 53 | global start_at, clf, X_train, y_train, X_test, y_test, score 54 | start_at = 0 55 | del clf 56 | clf = MLPClassifier(max_iter=200) 57 | for i in range(start_at, start_at+1): 58 | xt = X_train[i].reshape(1, -1) 59 | yt = y_train.values[[i]] 60 | clf = clf.partial_fit(xt, yt, classes=[0,1]) 61 | 62 | score = clf.score(X_test, y_test) 63 | 64 | start_at += 1 65 | 66 | response = {'result': float(round(score, 5)), 'remaining': len(X_train) - start_at} 67 | 68 | return jsonify(response) 69 | 70 | @app.route('/') 71 | def index(): 72 | global score, X_train 73 | rem = (len(X_train) - start_at) > 0 74 | 75 | return render_template("index.html", score=round(score, 5), remain = rem) 76 | 77 | if __name__ == '__main__': 78 | app.run() -------------------------------------------------------------------------------- /Chapter11/app/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==1.0.2 2 | Flask-Cors==3.0.7 3 | Flask-Jsonpify==1.5.0 4 | Flask-RESTful==0.3.7 5 | Flask-WTF==0.14.2 6 | gunicorn==19.9.0 7 | gym==0.14.0 8 | h5py==2.8.0 9 | heapdict==1.0.0 10 | html5lib==1.0.1 11 | httplib2==0.13.1 12 | hyperlink==18.0.0 13 | idna==2.8 14 | imageio==2.4.1 15 | imagesize==1.1.0 16 | importlib-metadata==0.6 17 | imutils==0.5.2 18 | incremental==17.5.0 19 | intervaltree==3.0.2 20 | numpy==1.17.1 21 | numpydoc==0.8.0 22 | oauth2client==4.1.3 23 | olefile==0.46 24 | packaging==18.0 25 | pandas==0.23.3 26 | pandocfilters==1.4.2 27 | parsel==1.5.1 28 | parso==0.3.1 29 | partd==0.3.9 30 | path.py==11.5.0 31 | pathlib2==2.3.3 32 | patsy==0.5.1 33 | pbr==5.1.3 34 | pep8==1.7.1 35 | pexpect==4.6.0 36 | pickleshare==0.7.5 37 | Pillow==6.2.0 38 | pkginfo==1.4.2 39 | pluggy==0.8.0 40 | ply==3.11 41 | prometheus-client==0.5.0 42 | promise==2.2.1 43 | prompt-toolkit==2.0.7 44 | protobuf==3.7.1 45 | psutil==5.4.8 46 | pyOpenSSL==18.0.0 47 | pyparsing==2.3.0 48 | pypng==0.0.20 49 | PySocks==1.6.8 50 | pytest==4.0.2 51 | pytest-arraydiff==0.3 52 | pytest-astropy==0.5.0 53 | pytest-doctestplus==0.2.0 54 | pytest-openfiles==0.3.1 55 | pytest-remotedata==0.3.1 56 | pytest-runner==4.4 57 | python-crontab==2.3.6 58 | python-dateutil==2.7.5 59 | python-Levenshtein==0.12.0 60 | python-utils==2.3.0 61 | pytz==2018.7 62 | PyYAML==3.13 63 | pyzmq==17.1.2 64 | QtAwesome==0.5.3 65 | qtconsole==4.4.3 66 | queuelib==1.5.0 67 | requests==2.21.0 68 | requests-file==1.4.3 69 | requests-toolbelt==0.9.1 70 | resampy==0.2.2 71 | rope==0.11.0 72 | rsa==4.0 73 | ruamel-yaml==0.15.46 74 | s3transfer==0.2.0 75 | scikit-image==0.14.1 76 | scikit-learn==0.21.3 77 | scipy==1.3.1 78 | Scrapy==1.5.2 79 | seaborn==0.9.0 80 | SecretStorage==3.1.0 81 | selenium==3.141.0 82 | Send2Trash==1.5.0 83 | service-identity==18.1.0 84 | simplegeneric==0.8.1 85 | singledispatch==3.4.0.3 86 | six==1.12.0 87 | sk-video==1.1.10 88 | sky==0.0.201 89 | snowballstemmer==1.2.1 90 | sonnet==0.1.6 91 | sortedcollections==1.0.1 92 | sortedcontainers==2.1.0 93 | SoundFile==0.10.2 94 | sox==1.3.7 95 | statsmodels==0.9.0 96 | sympy==1.3 97 | tables==3.4.4 98 | tblib==1.3.2 99 | termcolor==1.1.0 100 | terminado==0.8.1 101 | testpath==0.4.2 102 | tldextract==2.2.1 103 | toml==0.10.0 104 | toolz==0.9.0 105 | tornado==4.5.3 106 | tox==3.7.0 107 | tqdm==4.28.1 108 | traitlets==4.3.2 109 | twine==1.13.0 110 | Twisted==18.9.0 111 | unicodecsv==0.14.1 112 | uritemplate==3.0.0 113 | urllib3==1.24.1 114 | utils==0.9.0 115 | virtualenv==16.4.3 116 | w3lib==1.20.0 117 | wcwidth==0.1.7 118 | webencodings==0.5.1 119 | Werkzeug==0.14.1 120 | widgetsnbextension==3.4.2 121 | wrapt==1.10.11 122 | WTForms==2.2.1 123 | wurlitzer==1.0.2 124 | xlrd==1.2.0 125 | XlsxWriter==1.1.2 126 | xlwt==1.3.0 127 | yarl==1.3.0 128 | zict==0.1.3 129 | zope.interface==4.6.0 -------------------------------------------------------------------------------- /Chapter11/app/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Online Training Example 5 | 6 | 7 | 81 | 82 | 83 | 84 | 85 | 86 |
87 |
88 |
89 |
90 | Current Accuracy: {{ score }} 91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | {% if remain %} 99 | 100 | {% else %} 101 | 102 | {% endif %} 103 |
104 |
105 | 106 |
107 |
108 | 165 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/db.sqlite3 -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/ecomsite/__init__.py -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/ecomsite/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/__pycache__/settings.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/ecomsite/__pycache__/settings.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/ecomsite/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/__pycache__/wsgi.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/ecomsite/__pycache__/wsgi.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for ecomsite project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'cd83*9d_cm34n=lgi46rc&x*z3c3*n2fva&u9ak0uhuv0sz85(' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'orders', 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'ecomsite.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'ecomsite.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/urls.py: -------------------------------------------------------------------------------- 1 | """ecomsite path Configuration 2 | 3 | The `pathpatterns` list routes paths to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/paths/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a path to pathpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a path to pathpatterns: path('', Home.as_view(), name='home') 12 | Including another pathconf 13 | 1. Import the include() function: from django.paths import include, path 14 | 2. Add a path to pathpatterns: path('blog/', include('blog.paths')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('', include('orders.urls')), 21 | path('admin/', admin.site.urls), 22 | ] -------------------------------------------------------------------------------- /Chapter12/ecomsite/ecomsite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for ecomsite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecomsite.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecomsite.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__init__.py -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__pycache__/admin.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__pycache__/admin.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__pycache__/forms.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__pycache__/forms.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__pycache__/models.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__pycache__/models.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/__pycache__/views.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/__pycache__/views.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class OrdersConfig(AppConfig): 5 | name = 'orders' 6 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/forms.py: -------------------------------------------------------------------------------- 1 | from django.forms import ModelForm 2 | from django import forms 3 | from .models import Order 4 | 5 | class OrderForm(ModelForm): 6 | OPTIONS = ( 7 | ('Confirmed', 'Confirmed'), 8 | ('Shipping', 'Shipping'), 9 | ('Delivered', 'Delivered'), 10 | ) 11 | order_status = forms.TypedChoiceField(required=False, choices=OPTIONS, widget=forms.RadioSelect) 12 | 13 | class Meta: 14 | model = Order 15 | fields = ['name','phone','address','product_id','amount','order_status'] -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.5 on 2019-12-05 12:12 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Order', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('name', models.CharField(max_length=200)), 19 | ('phone', models.CharField(max_length=20)), 20 | ('address', models.TextField()), 21 | ('delivery_date', models.DateField(blank=True)), 22 | ('product_id', models.TextField()), 23 | ('amount', models.IntegerField()), 24 | ('order_status', models.CharField(max_length=50)), 25 | ], 26 | ), 27 | ] 28 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/migrations/0002_auto_20191205_1259.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.5 on 2019-12-05 12:59 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('orders', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.RemoveField( 14 | model_name='order', 15 | name='delivery_date', 16 | ), 17 | migrations.AlterField( 18 | model_name='order', 19 | name='name', 20 | field=models.CharField(max_length=500), 21 | ), 22 | migrations.AlterField( 23 | model_name='order', 24 | name='order_status', 25 | field=models.CharField(default='Confirmed', max_length=20), 26 | ), 27 | migrations.AlterField( 28 | model_name='order', 29 | name='phone', 30 | field=models.CharField(max_length=15), 31 | ), 32 | migrations.AlterField( 33 | model_name='order', 34 | name='product_id', 35 | field=models.IntegerField(), 36 | ), 37 | ] 38 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/migrations/__init__.py -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/migrations/__pycache__/0001_initial.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/migrations/__pycache__/0001_initial.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/migrations/__pycache__/0002_auto_20191205_1259.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/migrations/__pycache__/0002_auto_20191205_1259.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/migrations/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ecomsite/orders/migrations/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Order (models.Model): 5 | name = models.CharField(max_length=500) 6 | phone = models.CharField(max_length=15) 7 | address = models.TextField() 8 | product_id = models.IntegerField() 9 | amount = models.IntegerField() 10 | order_status = models.CharField(max_length=20, default="Confirmed") -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('', views.indexView, name='indexView'), 7 | path('', views.viewOrder, name='viewOrder'), 8 | path('add', views.addOrder, name='addOrder'), 9 | path('edit/', views.editOrder, name='editOrder'), 10 | path('delete/', views.deleteOrder, name='deleteOrder'), 11 | ] -------------------------------------------------------------------------------- /Chapter12/ecomsite/orders/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from .models import Order 3 | from .forms import OrderForm 4 | from django.http import JsonResponse 5 | 6 | def indexView(request): 7 | orders = Order.objects.all() 8 | orders = list(orders.values()) 9 | return JsonResponse({'orders': orders}) 10 | 11 | def viewOrder(request, orderId): 12 | order = Order.objects.filter(id=orderId) 13 | order = list(order.values()) 14 | return JsonResponse({'order': order}) 15 | 16 | def addOrder(request): 17 | if request.POST: 18 | form = OrderForm(request.POST) 19 | if form.is_valid(): 20 | if form.save(): 21 | return JsonResponse('Order created') 22 | else: 23 | return JsonResponse('There was an error') 24 | else: 25 | return JsonResponse('Invalid form details') 26 | else: 27 | return JsonResponse('Invalid form details') 28 | 29 | def editOrder(request, orderId): 30 | order = Order.objects.get(id=orderId) 31 | if request.POST: 32 | form = OrderForm(request.POST, instance=order) 33 | if form.is_valid(): 34 | if form.save(): 35 | return JsonResponse('Order updated') 36 | else: 37 | return JsonResponse('There was an error') 38 | else: 39 | return JsonResponse('Invalid form details') 40 | else: 41 | return JsonResponse('Invalid form details') 42 | 43 | def deleteOrder(request, orderId): 44 | order = Order.objects.get(id=orderId) 45 | order.delete() 46 | return JsonResponse('Order deleted') -------------------------------------------------------------------------------- /Chapter12/ordersui/Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn ordersui.wsgi -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/__init__.py -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/__pycache__/admin.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/__pycache__/admin.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/__pycache__/models.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/__pycache__/models.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/__pycache__/views.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/__pycache__/views.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiuiConfig(AppConfig): 5 | name = 'apiui' 6 | -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/migrations/__init__.py -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/migrations/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/apiui/migrations/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 27 |
28 |
29 | {% block body %} 30 | {% endblock %} 31 |
32 | 33 |
Ask a question
34 | 88 | 89 | -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% block title %} All Orders {% endblock %} 3 | {% block body %} 4 |
5 |
6 |
7 |
8 |
9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | {% for order in orders %} 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 36 | 37 | {% endfor %} 38 | 39 |
NamePhoneAddressProductAmountStatusButtons
{{ order.name }}{{ order.phone }}{{ order.address }}{{ order.product_id }}{{ order.amount }} {{ order.order_status }} 32 |
33 | View 34 |
35 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | {% endblock %} -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/templates/view.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% block title %} Print Order {% endblock %} 3 | {% block body %} 4 | {% for order in order %} 5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | {{ order.name }}
15 | {{ order.address }} 16 | Phone: {{ order.phone }} 17 |
18 |
19 | 20 |
21 |
22 |
23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
IDProduct IDTOTAL
1{{ order.product_id }}Rs. {{ order.amount }}
SubtotalRs. {{ order.amount }}
GSTRs. 0.00
TotalRs. {{ order.amount }}
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | {% endfor %} 63 | {% endblock %} -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('', views.indexView, name='indexView'), 7 | path('', views.viewOrder, name='viewOrder'), 8 | ] -------------------------------------------------------------------------------- /Chapter12/ordersui/apiui/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from django.contrib import messages 3 | import requests 4 | 5 | 6 | def indexView(request): 7 | URL = "https://b21588e3.ngrok.io" 8 | r = requests.get(url=URL) 9 | data = r.json() 10 | return render(request, 'index.html', context={'orders': data['orders']}) 11 | 12 | 13 | def viewOrder(request, orderId): 14 | URL = "https://b21588e3.ngrok.io/" + str(orderId) 15 | r = requests.get(url=URL) 16 | data = r.json() 17 | return render(request, 'view.html', {'order': data['order']}) -------------------------------------------------------------------------------- /Chapter12/ordersui/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ordersui.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/ordersui/__init__.py -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/ordersui/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/__pycache__/settings.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/ordersui/__pycache__/settings.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/ordersui/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/__pycache__/wsgi.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter12/ordersui/ordersui/__pycache__/wsgi.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for ordersui project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | import django_heroku 15 | 16 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 17 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18 | 19 | 20 | # Quick-start development settings - unsuitable for production 21 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 22 | 23 | # SECURITY WARNING: keep the secret key used in production secret! 24 | SECRET_KEY = '3@#!8y*%h$*)$!*j^6=g56d3mt7ex0&39hh6%y_gzm6r-x*ueq' 25 | 26 | # SECURITY WARNING: don't run with debug turned on in production! 27 | DEBUG = True 28 | 29 | ALLOWED_HOSTS = [] 30 | 31 | 32 | # Application definition 33 | 34 | INSTALLED_APPS = [ 35 | 'apiui', 36 | 'django.contrib.admin', 37 | 'django.contrib.auth', 38 | 'django.contrib.contenttypes', 39 | 'django.contrib.sessions', 40 | 'django.contrib.messages', 41 | 'django.contrib.staticfiles', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'ordersui.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'ordersui.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 77 | 78 | # DATABASES = { 79 | # 'default': { 80 | # 'ENGINE': 'django.db.backends.sqlite3', 81 | # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | # } 83 | # } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | django_heroku.settings(locals()) -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/urls.py: -------------------------------------------------------------------------------- 1 | """ordersui URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('', include('apiui.urls')), 21 | ] 22 | -------------------------------------------------------------------------------- /Chapter12/ordersui/ordersui/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for ordersui project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ordersui.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Chapter12/ordersui/requirements.txt: -------------------------------------------------------------------------------- 1 | django 2 | gunicorn 3 | django-heroku -------------------------------------------------------------------------------- /Chapter3/app/flask_app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | 3 | from scipy.misc import imread, imresize 4 | import numpy as np 5 | from keras.models import model_from_json 6 | import tensorflow as tf 7 | 8 | json_file = open('model.json','r') 9 | model_json = json_file.read() 10 | json_file.close() 11 | model = model_from_json(model_json) 12 | model.load_weights("weights.h5") 13 | model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) 14 | graph = tf.get_default_graph() 15 | 16 | app = Flask(__name__) 17 | 18 | @app.route('/') 19 | def index(): 20 | return render_template("index.html") 21 | 22 | import re 23 | import base64 24 | 25 | def convertImage(imgData1): 26 | imgstr = re.search(r'base64,(.*)', str(imgData1)).group(1) 27 | with open('output.png', 'wb') as output: 28 | output.write(base64.b64decode(imgstr)) 29 | 30 | @app.route('/predict/', methods=['GET', 'POST']) 31 | def predict(): 32 | global model, graph 33 | 34 | imgData = request.get_data() 35 | convertImage(imgData) 36 | 37 | x = imread('output.png', mode='L') 38 | 39 | x = imresize(x, (28, 28)) 40 | 41 | x = x.reshape(1, 28, 28, 1) 42 | with graph.as_default(): 43 | # perform the prediction 44 | out = model.predict(x) 45 | print(out) 46 | print(np.argmax(out, axis=1)) 47 | # convert the response to a string 48 | response = np.argmax(out, axis=1) 49 | return str(response[0]) 50 | 51 | 52 | if __name__ == "__main__": 53 | 54 | # run the app locally on the given port 55 | app.run(host='0.0.0.0', port=80) 56 | # optional if we want to run in debugging mode 57 | app.run(debug=True) 58 | -------------------------------------------------------------------------------- /Chapter3/app/flask_both.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | 3 | from scipy.misc import imread, imresize 4 | import numpy as np 5 | from keras.models import model_from_json 6 | import tensorflow as tf 7 | 8 | json_file = open('model.json','r') 9 | model_json = json_file.read() 10 | json_file.close() 11 | model = model_from_json(model_json) 12 | model.load_weights("weights.h5") 13 | model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) 14 | graph = tf.get_default_graph() 15 | 16 | app = Flask(__name__) 17 | 18 | @app.route('/') 19 | def index(): 20 | return render_template("index.html") 21 | 22 | import re 23 | import base64 24 | 25 | def convertImage(imgData1): 26 | imgstr = re.search(r'base64,(.*)', str(imgData1)).group(1) 27 | with open('output.png', 'wb') as output: 28 | output.write(base64.b64decode(imgstr)) 29 | 30 | @app.route('/predict/', methods=['GET', 'POST']) 31 | def predict(): 32 | global model, graph 33 | 34 | imgData = request.get_data() 35 | try: 36 | convertImage(imgData) 37 | except: 38 | f = request.files['img'] 39 | f.save('output.png') 40 | 41 | x = imread('output.png', mode='L') 42 | 43 | x = imresize(x, (28, 28)) 44 | 45 | x = x.reshape(1, 28, 28, 1) 46 | with graph.as_default(): 47 | # perform the prediction 48 | out = model.predict(x) 49 | print(out) 50 | print(np.argmax(out, axis=1)) 51 | # convert the response to a string 52 | response = np.argmax(out, axis=1) 53 | return str(response[0]) 54 | 55 | 56 | if __name__ == "__main__": 57 | 58 | # run the app locally on the given port 59 | app.run(host='0.0.0.0', port=80) 60 | # optional if we want to run in debugging mode 61 | app.run(debug=True) 62 | -------------------------------------------------------------------------------- /Chapter3/app/flask_cli.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | 3 | from scipy.misc import imread, imresize 4 | import numpy as np 5 | from keras.models import model_from_json 6 | import tensorflow as tf 7 | 8 | json_file = open('model.json','r') 9 | model_json = json_file.read() 10 | json_file.close() 11 | model = model_from_json(model_json) 12 | model.load_weights("weights.h5") 13 | model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) 14 | graph = tf.get_default_graph() 15 | 16 | app = Flask(__name__) 17 | 18 | @app.route('/') 19 | def index(): 20 | return render_template("index.html") 21 | 22 | @app.route('/predict/', methods=['GET', 'POST']) 23 | def predict(): 24 | global model, graph 25 | 26 | f = request.files['img'] 27 | f.save('output.png') 28 | 29 | x = imread('output.png', mode='L') 30 | 31 | x = imresize(x, (28, 28)) 32 | 33 | x = x.reshape(1, 28, 28, 1) 34 | with graph.as_default(): 35 | # perform the prediction 36 | out = model.predict(x) 37 | print(out) 38 | print(np.argmax(out, axis=1)) 39 | # convert the response to a string 40 | response = np.argmax(out, axis=1) 41 | return str(response[0]) 42 | 43 | 44 | if __name__ == "__main__": 45 | 46 | # run the app locally on the given port 47 | app.run(host='0.0.0.0', port=80) 48 | # optional if we want to run in debugging mode 49 | app.run(debug=True) 50 | -------------------------------------------------------------------------------- /Chapter3/app/model.json: -------------------------------------------------------------------------------- 1 | {"class_name": "Sequential", "config": {"name": "sequential_1", "layers": [{"class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "batch_input_shape": [null, 28, 28, 1], "dtype": "float32", "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_1", "trainable": true, "activation": "relu"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_2", "trainable": true, "activation": "relu"}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_3", "trainable": true, "filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_3", "trainable": true, "activation": "relu"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_4", "trainable": true, "filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_4", "trainable": true, "activation": "relu"}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Flatten", "config": {"name": "flatten_1", "trainable": true, "data_format": "channels_last"}}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "units": 512, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_5", "trainable": true, "activation": "relu"}}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "Dense", "config": {"name": "dense_2", "trainable": true, "units": 10, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_6", "trainable": true, "activation": "softmax"}}]}, "keras_version": "2.2.4", "backend": "tensorflow"} -------------------------------------------------------------------------------- /Chapter3/app/static/index.js: -------------------------------------------------------------------------------- 1 | (function() 2 | { 3 | var canvas = document.querySelector( "#canvas" ); 4 | var context = canvas.getContext( "2d" ); 5 | canvas.width = 280; 6 | canvas.height = 280; 7 | 8 | var Mouse = { x: 0, y: 0 }; 9 | var lastMouse = { x: 0, y: 0 }; 10 | context.fillStyle="black"; 11 | context.fillRect(0,0,canvas.width,canvas.height); 12 | context.color = "white"; 13 | context.lineWidth = 15; 14 | context.lineJoin = context.lineCap = 'round'; 15 | 16 | debug(); 17 | 18 | canvas.addEventListener( "mousemove", function( e ) 19 | { 20 | lastMouse.x = Mouse.x; 21 | lastMouse.y = Mouse.y; 22 | 23 | Mouse.x = e.pageX - this.offsetLeft; 24 | Mouse.y = e.pageY - this.offsetTop; 25 | 26 | }, false ); 27 | 28 | canvas.addEventListener( "mousedown", function( e ) 29 | { 30 | canvas.addEventListener( "mousemove", onPaint, false ); 31 | 32 | }, false ); 33 | 34 | canvas.addEventListener( "mouseup", function() 35 | { 36 | canvas.removeEventListener( "mousemove", onPaint, false ); 37 | 38 | }, false ); 39 | 40 | var onPaint = function() 41 | { 42 | context.lineWidth = context.lineWidth; 43 | context.lineJoin = "round"; 44 | context.lineCap = "round"; 45 | context.strokeStyle = context.color; 46 | 47 | context.beginPath(); 48 | context.moveTo( lastMouse.x, lastMouse.y ); 49 | context.lineTo( Mouse.x, Mouse.y ); 50 | context.closePath(); 51 | context.stroke(); 52 | }; 53 | 54 | function debug() 55 | { 56 | /* CLEAR BUTTON */ 57 | var clearButton = $( "#clearButton" ); 58 | 59 | clearButton.on( "click", function() 60 | { 61 | 62 | context.clearRect( 0, 0, 280, 280 ); 63 | context.fillStyle="black"; 64 | context.fillRect(0,0,canvas.width,canvas.height); 65 | 66 | }); 67 | 68 | /* LINE WIDTH */ 69 | 70 | var slider = document.getElementById("myRange"); 71 | var output = document.getElementById("sliderValue"); 72 | output.innerHTML = slider.value; 73 | 74 | slider.oninput = function() { 75 | output.innerHTML = this.value; 76 | context.lineWidth = $( this ).val(); 77 | } 78 | 79 | $( "#lineWidth" ).change(function() 80 | { 81 | context.lineWidth = $( this ).val(); 82 | }); 83 | } 84 | }()); 85 | -------------------------------------------------------------------------------- /Chapter3/app/static/style.css: -------------------------------------------------------------------------------- 1 | /* Space out content a bit */ 2 | body { 3 | padding-top: 20px; 4 | padding-bottom: 20px; 5 | } 6 | 7 | /* Everything but the jumbotron gets side spacing for mobile first views */ 8 | .header, 9 | .footer { 10 | padding-right: 15px; 11 | padding-left: 15px; 12 | } 13 | 14 | /* Custom page header */ 15 | .header { 16 | padding-bottom: 20px; 17 | border-bottom: 1px solid #e5e5e5; 18 | } 19 | /* Make the masthead heading the same height as the navigation */ 20 | .header h3 { 21 | margin-top: 0; 22 | margin-bottom: 0; 23 | line-height: 40px; 24 | } 25 | 26 | /* Custom page footer */ 27 | .footer { 28 | padding-top: 19px; 29 | color: #777; 30 | border-top: 1px solid #e5e5e5; 31 | } 32 | 33 | /* Customize container */ 34 | @media (min-width: 768px) { 35 | .container { 36 | max-width: 730px; 37 | } 38 | } 39 | .container-narrow > hr { 40 | margin: 30px 0; 41 | } 42 | 43 | /* Main marketing message and sign up button */ 44 | .jumbotron { 45 | text-align: center; 46 | border-bottom: 1px solid #e5e5e5; 47 | padding-top: 20px; 48 | padding-bottom: 20px; 49 | } 50 | 51 | .bodyDiv{ 52 | text-align: center; 53 | } 54 | 55 | @media screen and (min-width: 768px) { 56 | /* Remove the padding we set earlier */ 57 | .header, 58 | .footer { 59 | padding-right: 0; 60 | padding-left: 0; 61 | } 62 | /* Space out the masthead */ 63 | .header { 64 | margin-bottom: 30px; 65 | } 66 | /* Remove the bottom border on the jumbotron for visual effect */ 67 | .jumbotron { 68 | border-bottom: 0; 69 | } 70 | } 71 | 72 | @media screen and (max-width: 500px) { 73 | .slidecontainer{ 74 | display: none; 75 | } 76 | 77 | } 78 | 79 | .slidecontainer{ 80 | float: left; 81 | width: 30%; 82 | } 83 | 84 | .jumbotronHeading{ 85 | margin-bottom: 7vh; 86 | } 87 | 88 | .canvasDiv{ 89 | display: flow-root; 90 | text-align: center; 91 | } 92 | -------------------------------------------------------------------------------- /Chapter3/app/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | MNIST Handwritten text recognition using keras 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 |
22 | 28 |

MNIST Handwritten CNN

29 |
30 | 31 |
32 |

Draw the digit inside this Box!

33 |
34 |

Drag the slider to change the line width.

35 | 36 |

Value:

37 |
38 |
39 | 40 |
41 |

42 | Predict 43 | Clear 44 |

45 |
46 |
47 | 48 |
49 |

Get your prediction here!!!

50 |
51 | 52 |
53 |

© 2018, python36.com

54 |
55 | 56 |
57 | 58 | 59 | 60 | 61 | 62 | 63 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /Chapter3/app/weights.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter3/app/weights.h5 -------------------------------------------------------------------------------- /Chapter3/model/.ipynb_checkpoints/mnist-keras-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "_uuid": "18e73f61d4e40d59db0c0b1ecea56dc22d18e013" 8 | }, 9 | "outputs": [ 10 | { 11 | "name": "stderr", 12 | "output_type": "stream", 13 | "text": [ 14 | "Using TensorFlow backend.\n" 15 | ] 16 | } 17 | ], 18 | "source": [ 19 | "from __future__ import print_function\n", 20 | "import numpy as np\n", 21 | "import keras\n", 22 | "from keras.models import Sequential\n", 23 | "from keras.layers import Dense, Dropout, Flatten, Activation\n", 24 | "from keras.layers import Conv2D, MaxPooling2D\n", 25 | "from keras import backend as K\n", 26 | "from keras.layers.normalization import BatchNormalization\n", 27 | "import matplotlib.pyplot as plt\n", 28 | "%matplotlib inline\n", 29 | "losses = []" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 2, 35 | "metadata": { 36 | "_uuid": "4bbbe1bb5e72e9458e05590cd7719ff15af363a7" 37 | }, 38 | "outputs": [], 39 | "source": [ 40 | "def loadImageFile(fileimage):\n", 41 | " f = open(fileimage, \"rb\")\n", 42 | "\n", 43 | " f.read(16)\n", 44 | " pixels = 28*28\n", 45 | " images_arr = []\n", 46 | " \n", 47 | " while True:\n", 48 | " try:\n", 49 | " img = []\n", 50 | " for j in range(pixels):\n", 51 | " pix = ord(f.read(1))\n", 52 | " img.append(pix / 255)\n", 53 | " images_arr.append(img)\n", 54 | " except:\n", 55 | " break\n", 56 | "\n", 57 | " f.close()\n", 58 | " image_sets = np.array(images_arr)\n", 59 | " return image_sets" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 3, 65 | "metadata": { 66 | "_uuid": "c17196edfad2d9a8ce2f9be66e80496c209d18b7" 67 | }, 68 | "outputs": [], 69 | "source": [ 70 | "def loadLabelFile(filelabel):\n", 71 | " f = open(filelabel, \"rb\")\n", 72 | " f.read(8)\n", 73 | "\n", 74 | " labels_arr = []\n", 75 | "\n", 76 | " while True:\n", 77 | " row = [0 for x in range(10)]\n", 78 | " try:\n", 79 | " label = ord(f.read(1))\n", 80 | " row[label] = 1\n", 81 | " labels_arr.append(row)\n", 82 | " except:\n", 83 | " break\n", 84 | "\n", 85 | " f.close()\n", 86 | " label_sets = np.array(labels_arr)\n", 87 | " return label_sets" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 4, 93 | "metadata": { 94 | "_uuid": "09d093fb40e3d050a45ed7a582ed86f53fb97712" 95 | }, 96 | "outputs": [ 97 | { 98 | "ename": "FileNotFoundError", 99 | "evalue": "[Errno 2] No such file or directory: '../input/train-images-idx3-ubyte'", 100 | "output_type": "error", 101 | "traceback": [ 102 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 103 | "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", 104 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtrain_images\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mloadImageFile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"../input/train-images-idx3-ubyte\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mtrain_labels\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mloadLabelFile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"../input/train-labels-idx1-ubyte\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 105 | "\u001b[0;32m\u001b[0m in \u001b[0;36mloadImageFile\u001b[0;34m(fileimage)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mloadImageFile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfileimage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfileimage\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"rb\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m16\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mpixels\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m28\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0;36m28\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 106 | "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '../input/train-images-idx3-ubyte'" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "train_images = loadImageFile(\"../input/train-images-idx3-ubyte\")\n", 112 | "train_labels = loadLabelFile(\"../input/train-labels-idx1-ubyte\")" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": { 119 | "_uuid": "b11530b8eb21880e3a1efe87ee5f895b1c63ac6c" 120 | }, 121 | "outputs": [], 122 | "source": [ 123 | "test_images = loadImageFile(\"../input/t10k-images-idx3-ubyte\")\n", 124 | "test_labels = loadLabelFile(\"../input/t10k-labels-idx1-ubyte\")" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": { 131 | "_uuid": "ec284103fd067fe6a284bf767f3d446ba5891242" 132 | }, 133 | "outputs": [], 134 | "source": [ 135 | "x_train = train_images.reshape(train_images.shape[0], 28, 28, 1)\n", 136 | "x_test = test_images.reshape(test_images.shape[0], 28, 28, 1)\n", 137 | "\n", 138 | "y_train = train_labels\n", 139 | "y_test = test_labels" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": { 146 | "_uuid": "1461a5ae3b172ff0558cf4d529a1f3c1544e4093" 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "model = Sequential()" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": { 157 | "_uuid": "68d7d0522e3d08262c626e8ac40a90386a6735f1" 158 | }, 159 | "outputs": [], 160 | "source": [ 161 | "model.add(Conv2D(32, (3, 3), input_shape=(28,28,1)))\n", 162 | "model.add(Activation('relu'))\n", 163 | "BatchNormalization(axis=-1)\n", 164 | "model.add(Conv2D(32, (3, 3)))\n", 165 | "model.add(Activation('relu'))\n", 166 | "model.add(MaxPooling2D(pool_size=(2,2)))" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "metadata": { 173 | "_uuid": "8026bdf095bedcd7249edb1149ccf0005ae4d71c" 174 | }, 175 | "outputs": [], 176 | "source": [ 177 | "BatchNormalization(axis=-1)\n", 178 | "model.add(Conv2D(64,(3, 3)))\n", 179 | "model.add(Activation('relu'))\n", 180 | "BatchNormalization(axis=-1)\n", 181 | "model.add(Conv2D(64, (3, 3)))\n", 182 | "model.add(Activation('relu'))\n", 183 | "model.add(MaxPooling2D(pool_size=(2,2)))\n", 184 | "\n", 185 | "model.add(Flatten())\n", 186 | "# Fully connected layer\n", 187 | "\n", 188 | "BatchNormalization()\n", 189 | "model.add(Dense(512))\n", 190 | "model.add(Activation('relu'))\n", 191 | "BatchNormalization()\n", 192 | "model.add(Dropout(0.2))\n", 193 | "model.add(Dense(10))\n", 194 | "\n", 195 | "model.add(Activation('softmax'))" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": { 202 | "_uuid": "31a30bb3b861477e9a19446bf31c69999f4aff94" 203 | }, 204 | "outputs": [], 205 | "source": [ 206 | "model.compile(loss=keras.losses.categorical_crossentropy,\n", 207 | " optimizer=keras.optimizers.Adam(),\n", 208 | " metrics=['accuracy'])" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "metadata": { 215 | "_uuid": "8d0b56afd339355b60540d180bc980dfdcd9cfa6", 216 | "scrolled": true 217 | }, 218 | "outputs": [], 219 | "source": [ 220 | "model.fit(x_train, y_train,\n", 221 | " batch_size=100,\n", 222 | " epochs=10,\n", 223 | " verbose=2,\n", 224 | " validation_split=0.2)" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": null, 230 | "metadata": {}, 231 | "outputs": [], 232 | "source": [ 233 | "score = model.evaluate(x_test, y_test, verbose=1)\n", 234 | "\n", 235 | "print('Test loss:', score[0])\n", 236 | "print('Test accuracy:', score[1])" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": { 243 | "_uuid": "15f1b5e992bdaa163c6764e92b33f9596640081a" 244 | }, 245 | "outputs": [], 246 | "source": [ 247 | "# import os\n", 248 | "# os.mkdir(\"../output\")\n", 249 | "# model.save(\"../output/model.h5\")\n", 250 | "model.save_weights(\"weights.h5\")" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": { 257 | "_uuid": "3256139cde690795d5c60d340a79354360ca4032" 258 | }, 259 | "outputs": [], 260 | "source": [ 261 | "model_json = model.to_json()\n", 262 | "with open(\"model.json\", \"w\") as json_file:\n", 263 | " json_file.write(model_json)" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": null, 269 | "metadata": { 270 | "_uuid": "2615dbc51aeb523aec623e0253080ae3987793f3" 271 | }, 272 | "outputs": [], 273 | "source": [] 274 | } 275 | ], 276 | "metadata": { 277 | "kernelspec": { 278 | "display_name": "Python 3", 279 | "language": "python", 280 | "name": "python3" 281 | }, 282 | "language_info": { 283 | "codemirror_mode": { 284 | "name": "ipython", 285 | "version": 3 286 | }, 287 | "file_extension": ".py", 288 | "mimetype": "text/x-python", 289 | "name": "python", 290 | "nbconvert_exporter": "python", 291 | "pygments_lexer": "ipython3", 292 | "version": "3.7.4" 293 | } 294 | }, 295 | "nbformat": 4, 296 | "nbformat_minor": 1 297 | } 298 | -------------------------------------------------------------------------------- /Chapter3/model/mnist-keras.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "_uuid": "18e73f61d4e40d59db0c0b1ecea56dc22d18e013" 8 | }, 9 | "outputs": [ 10 | { 11 | "name": "stderr", 12 | "output_type": "stream", 13 | "text": [ 14 | "Using TensorFlow backend.\n" 15 | ] 16 | } 17 | ], 18 | "source": [ 19 | "from __future__ import print_function\n", 20 | "import numpy as np\n", 21 | "import keras\n", 22 | "from keras.models import Sequential\n", 23 | "from keras.layers import Dense, Dropout, Flatten, Activation\n", 24 | "from keras.layers import Conv2D, MaxPooling2D\n", 25 | "from keras import backend as K\n", 26 | "from keras.layers.normalization import BatchNormalization\n", 27 | "import matplotlib.pyplot as plt\n", 28 | "%matplotlib inline\n", 29 | "losses = []" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 2, 35 | "metadata": { 36 | "_uuid": "4bbbe1bb5e72e9458e05590cd7719ff15af363a7" 37 | }, 38 | "outputs": [], 39 | "source": [ 40 | "def loadImageFile(fileimage):\n", 41 | " f = open(fileimage, \"rb\")\n", 42 | "\n", 43 | " f.read(16)\n", 44 | " pixels = 28*28\n", 45 | " images_arr = []\n", 46 | " \n", 47 | " while True:\n", 48 | " try:\n", 49 | " img = []\n", 50 | " for j in range(pixels):\n", 51 | " pix = ord(f.read(1))\n", 52 | " img.append(pix / 255)\n", 53 | " images_arr.append(img)\n", 54 | " except:\n", 55 | " break\n", 56 | "\n", 57 | " f.close()\n", 58 | " image_sets = np.array(images_arr)\n", 59 | " return image_sets" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 3, 65 | "metadata": { 66 | "_uuid": "c17196edfad2d9a8ce2f9be66e80496c209d18b7" 67 | }, 68 | "outputs": [], 69 | "source": [ 70 | "def loadLabelFile(filelabel):\n", 71 | " f = open(filelabel, \"rb\")\n", 72 | " f.read(8)\n", 73 | "\n", 74 | " labels_arr = []\n", 75 | "\n", 76 | " while True:\n", 77 | " row = [0 for x in range(10)]\n", 78 | " try:\n", 79 | " label = ord(f.read(1))\n", 80 | " row[label] = 1\n", 81 | " labels_arr.append(row)\n", 82 | " except:\n", 83 | " break\n", 84 | "\n", 85 | " f.close()\n", 86 | " label_sets = np.array(labels_arr)\n", 87 | " return label_sets" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 4, 93 | "metadata": { 94 | "_uuid": "09d093fb40e3d050a45ed7a582ed86f53fb97712" 95 | }, 96 | "outputs": [ 97 | { 98 | "ename": "FileNotFoundError", 99 | "evalue": "[Errno 2] No such file or directory: '../input/train-images-idx3-ubyte'", 100 | "output_type": "error", 101 | "traceback": [ 102 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 103 | "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", 104 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtrain_images\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mloadImageFile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"../input/train-images-idx3-ubyte\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mtrain_labels\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mloadLabelFile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"../input/train-labels-idx1-ubyte\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 105 | "\u001b[0;32m\u001b[0m in \u001b[0;36mloadImageFile\u001b[0;34m(fileimage)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mloadImageFile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfileimage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfileimage\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"rb\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m16\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mpixels\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m28\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0;36m28\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 106 | "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '../input/train-images-idx3-ubyte'" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "train_images = loadImageFile(\"../input/train-images-idx3-ubyte\")\n", 112 | "train_labels = loadLabelFile(\"../input/train-labels-idx1-ubyte\")" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": { 119 | "_uuid": "b11530b8eb21880e3a1efe87ee5f895b1c63ac6c" 120 | }, 121 | "outputs": [], 122 | "source": [ 123 | "test_images = loadImageFile(\"../input/t10k-images-idx3-ubyte\")\n", 124 | "test_labels = loadLabelFile(\"../input/t10k-labels-idx1-ubyte\")" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": { 131 | "_uuid": "ec284103fd067fe6a284bf767f3d446ba5891242" 132 | }, 133 | "outputs": [], 134 | "source": [ 135 | "x_train = train_images.reshape(train_images.shape[0], 28, 28, 1)\n", 136 | "x_test = test_images.reshape(test_images.shape[0], 28, 28, 1)\n", 137 | "\n", 138 | "y_train = train_labels\n", 139 | "y_test = test_labels" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": { 146 | "_uuid": "1461a5ae3b172ff0558cf4d529a1f3c1544e4093" 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "model = Sequential()" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": { 157 | "_uuid": "68d7d0522e3d08262c626e8ac40a90386a6735f1" 158 | }, 159 | "outputs": [], 160 | "source": [ 161 | "model.add(Conv2D(32, (3, 3), input_shape=(28,28,1)))\n", 162 | "model.add(Activation('relu'))\n", 163 | "BatchNormalization(axis=-1)\n", 164 | "model.add(Conv2D(32, (3, 3)))\n", 165 | "model.add(Activation('relu'))\n", 166 | "model.add(MaxPooling2D(pool_size=(2,2)))" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "metadata": { 173 | "_uuid": "8026bdf095bedcd7249edb1149ccf0005ae4d71c" 174 | }, 175 | "outputs": [], 176 | "source": [ 177 | "BatchNormalization(axis=-1)\n", 178 | "model.add(Conv2D(64,(3, 3)))\n", 179 | "model.add(Activation('relu'))\n", 180 | "BatchNormalization(axis=-1)\n", 181 | "model.add(Conv2D(64, (3, 3)))\n", 182 | "model.add(Activation('relu'))\n", 183 | "model.add(MaxPooling2D(pool_size=(2,2)))\n", 184 | "\n", 185 | "model.add(Flatten())\n", 186 | "# Fully connected layer\n", 187 | "\n", 188 | "BatchNormalization()\n", 189 | "model.add(Dense(512))\n", 190 | "model.add(Activation('relu'))\n", 191 | "BatchNormalization()\n", 192 | "model.add(Dropout(0.2))\n", 193 | "model.add(Dense(10))\n", 194 | "\n", 195 | "model.add(Activation('softmax'))" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": { 202 | "_uuid": "31a30bb3b861477e9a19446bf31c69999f4aff94" 203 | }, 204 | "outputs": [], 205 | "source": [ 206 | "model.compile(loss=keras.losses.categorical_crossentropy,\n", 207 | " optimizer=keras.optimizers.Adam(),\n", 208 | " metrics=['accuracy'])" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "metadata": { 215 | "_uuid": "8d0b56afd339355b60540d180bc980dfdcd9cfa6", 216 | "scrolled": true 217 | }, 218 | "outputs": [], 219 | "source": [ 220 | "model.fit(x_train, y_train,\n", 221 | " batch_size=100,\n", 222 | " epochs=10,\n", 223 | " verbose=2,\n", 224 | " validation_split=0.2)" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": null, 230 | "metadata": {}, 231 | "outputs": [], 232 | "source": [ 233 | "score = model.evaluate(x_test, y_test, verbose=1)\n", 234 | "\n", 235 | "print('Test loss:', score[0])\n", 236 | "print('Test accuracy:', score[1])" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": { 243 | "_uuid": "15f1b5e992bdaa163c6764e92b33f9596640081a" 244 | }, 245 | "outputs": [], 246 | "source": [ 247 | "# import os\n", 248 | "# os.mkdir(\"../output\")\n", 249 | "# model.save(\"../output/model.h5\")\n", 250 | "model.save_weights(\"weights.h5\")" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": { 257 | "_uuid": "3256139cde690795d5c60d340a79354360ca4032" 258 | }, 259 | "outputs": [], 260 | "source": [ 261 | "model_json = model.to_json()\n", 262 | "with open(\"model.json\", \"w\") as json_file:\n", 263 | " json_file.write(model_json)" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": null, 269 | "metadata": { 270 | "_uuid": "2615dbc51aeb523aec623e0253080ae3987793f3" 271 | }, 272 | "outputs": [], 273 | "source": [] 274 | } 275 | ], 276 | "metadata": { 277 | "kernelspec": { 278 | "display_name": "Python 3", 279 | "language": "python", 280 | "name": "python3" 281 | }, 282 | "language_info": { 283 | "codemirror_mode": { 284 | "name": "ipython", 285 | "version": 3 286 | }, 287 | "file_extension": ".py", 288 | "mimetype": "text/x-python", 289 | "name": "python", 290 | "nbconvert_exporter": "python", 291 | "pygments_lexer": "ipython3", 292 | "version": "3.7.4" 293 | } 294 | }, 295 | "nbformat": 4, 296 | "nbformat_minor": 1 297 | } 298 | -------------------------------------------------------------------------------- /Chapter4/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /Chapter4/README.md: -------------------------------------------------------------------------------- 1 | # tfjs-iris 2 | 3 | Steps to use the code in this directory - 4 | 5 | - 1. Clone the repo 6 | - 2. cd into `Chapter4` 7 | - 3. in a terminal, use `npm install` 8 | - 4. in a terminal, use `npm index.js` 9 | - 5. go to browser: (localhost:3000)[http://localhost:3000] 10 | - 6. Click on Train button 11 | - 7. Click on Predict button 12 | -------------------------------------------------------------------------------- /Chapter4/index.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | const tf = require('@tensorflow/tfjs'); 5 | const iris = require('./iris.json'); 6 | 7 | tf.disableDeprecationWarnings(); 8 | 9 | const trainingData = tf.tensor2d(iris.map(item=> [ 10 | item.sepal_length, item.sepal_width, item.petal_length, item.petal_width 11 | ] 12 | ),[144,4]) 13 | 14 | const outputData = tf.tensor2d(iris.map(item => [ 15 | item.species === 'setosa' ? 1 : 0, 16 | item.species === 'virginica' ? 1 : 0, 17 | item.species === 'versicolor' ? 1 : 0 18 | 19 | ]), [144,3]) 20 | 21 | const model = tf.sequential(); 22 | 23 | 24 | model.add(tf.layers.dense( 25 | { inputShape: 4, 26 | activation: 'sigmoid', 27 | units: 10 28 | } 29 | )); 30 | 31 | model.add(tf.layers.dense( 32 | { 33 | inputShape: 10, 34 | units: 3, 35 | activation: 'softmax' 36 | } 37 | )); 38 | 39 | model.summary(); 40 | 41 | model.compile({ 42 | loss: "categoricalCrossentropy", 43 | optimizer: tf.train.adam() 44 | }); 45 | 46 | async function train_data(){ 47 | 48 | console.log("Training Started"); 49 | for(let i=0;i<50;i++){ 50 | let res = await model.fit(trainingData, outputData, {epochs: 50}); 51 | console.log(`Iteration ${i}: ${res.history.loss[0]}`); 52 | } 53 | console.log("Training Complete"); 54 | } 55 | 56 | app.use(express.static('./public')).get('/', function (req, res) { 57 | res.sendFile('./index.html'); 58 | }); 59 | 60 | var bodyParser = require('body-parser'); 61 | 62 | app.use(bodyParser.urlencoded({ extended: false })); 63 | 64 | app.post('/predict', function(req, res) { 65 | 66 | var test = tf.tensor2d([parseFloat(req.body.sepLen), parseFloat(req.body.sepWid), parseFloat(req.body.petLen), parseFloat(req.body.petWid)], [1,4]); 67 | 68 | var out = model.predict(test); 69 | 70 | var maxIndex = 0; 71 | for (let i=1;i out.buffer().get(0, maxIndex)){ 73 | maxIndex = i; 74 | } 75 | } 76 | 77 | // console.log(maxIndex); 78 | 79 | ans = "Undetermined"; 80 | 81 | switch(maxIndex) { 82 | case 0: 83 | ans = "Setosa"; 84 | break; 85 | case 1: 86 | ans = "Virginica"; 87 | break; 88 | case 2: 89 | ans = "Versicolor"; 90 | break; 91 | } 92 | 93 | console.log(ans); 94 | 95 | res.send(ans); 96 | 97 | }); 98 | 99 | var doTrain = async function (req, res, next) { 100 | await train_data(); 101 | next(); 102 | } 103 | 104 | app.use(doTrain).post('/train', function(req, res) { 105 | res.send("1"); 106 | }); 107 | 108 | app.listen(3000); -------------------------------------------------------------------------------- /Chapter4/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Chapter4", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@tensorflow/tfjs": "^0.15.1", 14 | "@tensorflow/tfjs-node": "^0.3.0", 15 | "body-parser": "^1.18.3", 16 | "express": "^4.16.4" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter4/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | TensorFlow.js Example - Iris Flower Classficiation 4 | 5 | 6 |

TensorFlow.js Example - Iris Flower Classification

7 |
8 |

9 | First, train the model. Then, use the text boxes to try any dummy data. 10 |

11 | 12 | 13 | 14 |

15 | 16 |
17 | 18 |
19 | 20 |
21 | 22 |
23 |
24 | 25 |
26 |

Result

27 |

28 | 29 | 30 | 62 | 63 | -------------------------------------------------------------------------------- /Chapter6/CloudVisionClientExample/.ipynb_checkpoints/CloudVisionAPIExample-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 5, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from google.cloud import vision" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 6, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "client = vision.ImageAnnotatorClient()" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 7, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "with open(\"test.jpg\", 'rb') as image_file:\n", 28 | " content = image_file.read()" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 8, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "image = vision.types.Image(content=content)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 9, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "response = client.label_detection(image=image)\n", 47 | "labels = response.label_annotations" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 10, 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "Labels:\n", 60 | "Sky\n", 61 | "Horizon\n", 62 | "Atmosphere\n", 63 | "Sunrise\n", 64 | "Sunset\n", 65 | "Morning\n", 66 | "Ocean\n", 67 | "Calm\n", 68 | "Wing\n", 69 | "Evening\n" 70 | ] 71 | } 72 | ], 73 | "source": [ 74 | "print('Labels:')\n", 75 | "for label in labels:\n", 76 | " print(label.description)" 77 | ] 78 | } 79 | ], 80 | "metadata": { 81 | "kernelspec": { 82 | "display_name": "Python 3", 83 | "language": "python", 84 | "name": "python3" 85 | }, 86 | "language_info": { 87 | "codemirror_mode": { 88 | "name": "ipython", 89 | "version": 3 90 | }, 91 | "file_extension": ".py", 92 | "mimetype": "text/x-python", 93 | "name": "python", 94 | "nbconvert_exporter": "python", 95 | "pygments_lexer": "ipython3", 96 | "version": "3.7.0" 97 | } 98 | }, 99 | "nbformat": 4, 100 | "nbformat_minor": 2 101 | } 102 | -------------------------------------------------------------------------------- /Chapter6/CloudVisionClientExample/CloudVisionAPIExample.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 5, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from google.cloud import vision" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 6, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "client = vision.ImageAnnotatorClient()" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 7, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "with open(\"test.jpg\", 'rb') as image_file:\n", 28 | " content = image_file.read()" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 8, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "image = vision.types.Image(content=content)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 9, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "response = client.label_detection(image=image)\n", 47 | "labels = response.label_annotations" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 10, 53 | "metadata": { 54 | "scrolled": true 55 | }, 56 | "outputs": [ 57 | { 58 | "name": "stdout", 59 | "output_type": "stream", 60 | "text": [ 61 | "Labels:\n", 62 | "Sky\n", 63 | "Horizon\n", 64 | "Atmosphere\n", 65 | "Sunrise\n", 66 | "Sunset\n", 67 | "Morning\n", 68 | "Ocean\n", 69 | "Calm\n", 70 | "Wing\n", 71 | "Evening\n" 72 | ] 73 | } 74 | ], 75 | "source": [ 76 | "print('Labels:')\n", 77 | "for label in labels:\n", 78 | " print(label.description)" 79 | ] 80 | } 81 | ], 82 | "metadata": { 83 | "kernelspec": { 84 | "display_name": "Python 3", 85 | "language": "python", 86 | "name": "python3" 87 | }, 88 | "language_info": { 89 | "codemirror_mode": { 90 | "name": "ipython", 91 | "version": 3 92 | }, 93 | "file_extension": ".py", 94 | "mimetype": "text/x-python", 95 | "name": "python", 96 | "nbconvert_exporter": "python", 97 | "pygments_lexer": "ipython3", 98 | "version": "3.7.0" 99 | } 100 | }, 101 | "nbformat": 4, 102 | "nbformat_minor": 2 103 | } 104 | -------------------------------------------------------------------------------- /Chapter6/CloudVisionClientExample/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter6/CloudVisionClientExample/test.jpg -------------------------------------------------------------------------------- /Chapter6/DialogFlow_Python_API_Example/.ipynb_checkpoints/DialogFlowTestIntent-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import dialogflow\n", 10 | "import os" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "session_client = dialogflow.SessionsClient()" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 3, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "def detect_intent_texts(session_client, project_id, session_id, text, language_code):\n", 29 | " session = session_client.session_path(project_id, session_id)\n", 30 | "\n", 31 | " if text:\n", 32 | " text_input = dialogflow.types.TextInput(\n", 33 | " text=text, language_code=language_code)\n", 34 | " query_input = dialogflow.types.QueryInput(text=text_input)\n", 35 | " response = session_client.detect_intent(\n", 36 | " session=session, query_input=query_input)\n", 37 | "\n", 38 | " return response.query_result.fulfillment_text" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": 5, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "project_id = os.getenv(\"DIALOGFLOW_PROJECT_ID\")" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 9, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "message = \"Can I talk to the dummy?\"" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 10, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "fulfillment_text = detect_intent_texts(project_id, \"unique\", message, 'en')\n", 66 | "response_text = { \"message\": fulfillment_text }" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 11, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "data": { 76 | "text/plain": [ 77 | "{'message': 'Congratulations, dummy intent user!'}" 78 | ] 79 | }, 80 | "execution_count": 11, 81 | "metadata": {}, 82 | "output_type": "execute_result" 83 | } 84 | ], 85 | "source": [ 86 | "response_text" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [] 95 | } 96 | ], 97 | "metadata": { 98 | "kernelspec": { 99 | "display_name": "Python 3", 100 | "language": "python", 101 | "name": "python3" 102 | }, 103 | "language_info": { 104 | "codemirror_mode": { 105 | "name": "ipython", 106 | "version": 3 107 | }, 108 | "file_extension": ".py", 109 | "mimetype": "text/x-python", 110 | "name": "python", 111 | "nbconvert_exporter": "python", 112 | "pygments_lexer": "ipython3", 113 | "version": "3.7.0" 114 | } 115 | }, 116 | "nbformat": 4, 117 | "nbformat_minor": 2 118 | } 119 | -------------------------------------------------------------------------------- /Chapter6/DialogFlow_Python_API_Example/.ipynb_checkpoints/Untitled-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 2 6 | } 7 | -------------------------------------------------------------------------------- /Chapter6/DialogFlow_Python_API_Example/DialogFlowTestIntent.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import dialogflow" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import os\n", 19 | "project_id = os.getenv(\"DIALOGFLOW_PROJECT_ID\")" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 3, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "session_id=\"unique\"" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 4, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "def detect_intent(project_id, session_id, text, language_code):\n", 38 | " \n", 39 | " session_client = dialogflow.SessionsClient()\n", 40 | " session = session_client.session_path(project_id, session_id)\n", 41 | " \n", 42 | " text_input = dialogflow.types.TextInput(text=text, language_code=language_code)\n", 43 | " query_input = dialogflow.types.QueryInput(text=text_input)\n", 44 | " response = session_client.detect_intent(session=session, query_input=query_input)\n", 45 | " \n", 46 | " print(response)\n", 47 | " \n", 48 | " return response.query_result.fulfillment_text" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": 7, 54 | "metadata": {}, 55 | "outputs": [ 56 | { 57 | "name": "stdout", 58 | "output_type": "stream", 59 | "text": [ 60 | "response_id: \"d1a7b2bf-8c5e-4c3d-91be-81161394cc24\"\n", 61 | "query_result {\n", 62 | " query_text: \"talk to the dummy?\"\n", 63 | " parameters {\n", 64 | " }\n", 65 | " all_required_params_present: true\n", 66 | " fulfillment_text: \"Congratulations, dummy intent user!\"\n", 67 | " fulfillment_messages {\n", 68 | " text {\n", 69 | " text: \"Congratulations, dummy intent user!\"\n", 70 | " }\n", 71 | " }\n", 72 | " intent {\n", 73 | " name: \"projects/gcp-api-232806/agent/intents/35e15aa5-e433-400f-a9d6-672d46bcefa7\"\n", 74 | " display_name: \"Dummy Intent\"\n", 75 | " }\n", 76 | " intent_detection_confidence: 0.8199999928474426\n", 77 | " language_code: \"en\"\n", 78 | "}\n", 79 | "\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "message = \"talk to the dummy?\"\n", 85 | "fulfillment_text = detect_intent(project_id, session_id, message, 'en')" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 8, 91 | "metadata": {}, 92 | "outputs": [ 93 | { 94 | "name": "stdout", 95 | "output_type": "stream", 96 | "text": [ 97 | "Congratulations, dummy intent user!\n" 98 | ] 99 | } 100 | ], 101 | "source": [ 102 | "print(fulfillment_text)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [] 111 | } 112 | ], 113 | "metadata": { 114 | "kernelspec": { 115 | "display_name": "Python 3", 116 | "language": "python", 117 | "name": "python3" 118 | }, 119 | "language_info": { 120 | "codemirror_mode": { 121 | "name": "ipython", 122 | "version": 3 123 | }, 124 | "file_extension": ".py", 125 | "mimetype": "text/x-python", 126 | "name": "python", 127 | "nbconvert_exporter": "python", 128 | "pygments_lexer": "ipython3", 129 | "version": "3.7.0" 130 | } 131 | }, 132 | "nbformat": 4, 133 | "nbformat_minor": 2 134 | } 135 | -------------------------------------------------------------------------------- /Chapter6/GoogleCloudTranslateExample/.ipynb_checkpoints/CloudTranslateAPIExample-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from google.cloud import translate" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "translate_client = translate.Client()" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 8, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "original = u'नमस्ते'" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 10, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "translation = translate_client.translate(original, target_language=\"en\")" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 13, 42 | "metadata": {}, 43 | "outputs": [ 44 | { 45 | "data": { 46 | "text/plain": [ 47 | "{'translatedText': 'Hello', 'detectedSourceLanguage': 'hi', 'input': 'नमस्ते'}" 48 | ] 49 | }, 50 | "execution_count": 13, 51 | "metadata": {}, 52 | "output_type": "execute_result" 53 | } 54 | ], 55 | "source": [ 56 | "translation" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 14, 62 | "metadata": {}, 63 | "outputs": [ 64 | { 65 | "name": "stdout", 66 | "output_type": "stream", 67 | "text": [ 68 | "Original: नमस्ते\n", 69 | "Translation: Hello\n", 70 | "Detected Language: hi\n" 71 | ] 72 | } 73 | ], 74 | "source": [ 75 | "print(u'Original: {}'.format(original))\n", 76 | "print(u'Translation: {}'.format(translation['translatedText']))\n", 77 | "print(u'Detected Language: {}'.format(translation['detectedSourceLanguage']))" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [] 86 | } 87 | ], 88 | "metadata": { 89 | "kernelspec": { 90 | "display_name": "Python 3", 91 | "language": "python", 92 | "name": "python3" 93 | }, 94 | "language_info": { 95 | "codemirror_mode": { 96 | "name": "ipython", 97 | "version": 3 98 | }, 99 | "file_extension": ".py", 100 | "mimetype": "text/x-python", 101 | "name": "python", 102 | "nbconvert_exporter": "python", 103 | "pygments_lexer": "ipython3", 104 | "version": "3.7.0" 105 | } 106 | }, 107 | "nbformat": 4, 108 | "nbformat_minor": 2 109 | } 110 | -------------------------------------------------------------------------------- /Chapter6/GoogleCloudTranslateExample/CloudTranslateAPIExample.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from google.cloud import translate" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "translate_client = translate.Client()" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 8, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "original = u'नमस्ते'" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 10, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "translation = translate_client.translate(original, target_language=\"en\")" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 13, 42 | "metadata": {}, 43 | "outputs": [ 44 | { 45 | "data": { 46 | "text/plain": [ 47 | "{'translatedText': 'Hello', 'detectedSourceLanguage': 'hi', 'input': 'नमस्ते'}" 48 | ] 49 | }, 50 | "execution_count": 13, 51 | "metadata": {}, 52 | "output_type": "execute_result" 53 | } 54 | ], 55 | "source": [ 56 | "translation" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 14, 62 | "metadata": {}, 63 | "outputs": [ 64 | { 65 | "name": "stdout", 66 | "output_type": "stream", 67 | "text": [ 68 | "Original: नमस्ते\n", 69 | "Translation: Hello\n", 70 | "Detected Language: hi\n" 71 | ] 72 | } 73 | ], 74 | "source": [ 75 | "print(u'Original: {}'.format(original))\n", 76 | "print(u'Translation: {}'.format(translation['translatedText']))\n", 77 | "print(u'Detected Language: {}'.format(translation['detectedSourceLanguage']))" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [] 86 | } 87 | ], 88 | "metadata": { 89 | "kernelspec": { 90 | "display_name": "Python 3", 91 | "language": "python", 92 | "name": "python3" 93 | }, 94 | "language_info": { 95 | "codemirror_mode": { 96 | "name": "ipython", 97 | "version": 3 98 | }, 99 | "file_extension": ".py", 100 | "mimetype": "text/x-python", 101 | "name": "python", 102 | "nbconvert_exporter": "python", 103 | "pygments_lexer": "ipython3", 104 | "version": "3.7.0" 105 | } 106 | }, 107 | "nbformat": 4, 108 | "nbformat_minor": 2 109 | } 110 | -------------------------------------------------------------------------------- /Chapter7/AlexaSkillExample/lambda_function.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import json 3 | 4 | 5 | import random 6 | import uuid 7 | 8 | import time 9 | 10 | 11 | def get_utc_timestamp(seconds=None): 12 | return time.strftime('%Y-%m-%dT%H:%M:%S.00Z', time.gmtime(seconds)) 13 | 14 | 15 | class AlexaResponse: 16 | 17 | def __init__(self, **kwargs): 18 | 19 | self.context_properties = [] 20 | self.payload_endpoints = [] 21 | 22 | # Set up the response structure 23 | self.context = {} 24 | self.event = { 25 | 'header': { 26 | 'namespace': kwargs.get('namespace', 'Alexa'), 27 | 'name': kwargs.get('name', 'Response'), 28 | 'messageId': str(uuid.uuid4()), 29 | 'payloadVersion': kwargs.get('payload_version', '3') 30 | # 'correlation_token': kwargs.get('correlation_token', 'INVALID') 31 | }, 32 | 'endpoint': { 33 | "scope": { 34 | "type": "BearerToken", 35 | "token": kwargs.get('token', 'INVALID') 36 | }, 37 | "endpointId": kwargs.get('endpoint_id', 'INVALID') 38 | }, 39 | 'payload': kwargs.get('payload', {}) 40 | } 41 | 42 | if 'correlation_token' in kwargs: 43 | self.event['header']['correlation_token'] = kwargs.get('correlation_token', 'INVALID') 44 | 45 | if 'cookie' in kwargs: 46 | self.event['endpoint']['cookie'] = kwargs.get('cookie', '{}') 47 | 48 | # No endpoint in an AcceptGrant or Discover request 49 | if self.event['header']['name'] == 'AcceptGrant.Response' or self.event['header']['name'] == 'Discover.Response': 50 | self.event.pop('endpoint') 51 | 52 | def add_context_property(self, **kwargs): 53 | self.context_properties.append(self.create_context_property(**kwargs)) 54 | 55 | def add_cookie(self, key, value): 56 | 57 | if "cookies" in self is None: 58 | self.cookies = {} 59 | 60 | self.cookies[key] = value 61 | 62 | def add_payload_endpoint(self, **kwargs): 63 | self.payload_endpoints.append(self.create_payload_endpoint(**kwargs)) 64 | 65 | def create_context_property(self, **kwargs): 66 | return { 67 | 'namespace': kwargs.get('namespace', 'Alexa.EndpointHealth'), 68 | 'name': kwargs.get('name', 'connectivity'), 69 | 'value': kwargs.get('value', {'value': 'OK'}), 70 | 'timeOfSample': get_utc_timestamp(), 71 | 'uncertaintyInMilliseconds': kwargs.get('uncertainty_in_milliseconds', 0) 72 | } 73 | 74 | def create_payload_endpoint(self, **kwargs): 75 | # Return the proper structure expected for the endpoint 76 | endpoint = { 77 | 'capabilities': kwargs.get('capabilities', []), 78 | 'description': kwargs.get('description', 'Sample Endpoint Description'), 79 | 'displayCategories': kwargs.get('display_categories', ['OTHER']), 80 | 'endpointId': kwargs.get('endpoint_id', 'endpoint_' + "%0.6d" % random.randint(0, 999999)), 81 | 'friendlyName': kwargs.get('friendly_name', 'Sample Endpoint'), 82 | 'manufacturerName': kwargs.get('manufacturer_name', 'Sample Manufacturer') 83 | } 84 | 85 | if 'cookie' in kwargs: 86 | endpoint['cookie'] = kwargs.get('cookie', {}) 87 | 88 | return endpoint 89 | 90 | def create_payload_endpoint_capability(self, **kwargs): 91 | capability = { 92 | 'type': kwargs.get('type', 'AlexaInterface'), 93 | 'interface': kwargs.get('interface', 'Alexa'), 94 | 'version': kwargs.get('version', '3') 95 | } 96 | supported = kwargs.get('supported', None) 97 | if supported: 98 | capability['properties'] = {} 99 | capability['properties']['supported'] = supported 100 | capability['properties']['proactivelyReported'] = kwargs.get('proactively_reported', True) 101 | capability['properties']['retrievable'] = kwargs.get('retrievable', True) 102 | return capability 103 | 104 | def get(self, remove_empty=True): 105 | 106 | response = { 107 | 'context': self.context, 108 | 'event': self.event 109 | } 110 | 111 | if len(self.context_properties) > 0: 112 | response['context']['properties'] = self.context_properties 113 | 114 | if len(self.payload_endpoints) > 0: 115 | response['event']['payload']['endpoints'] = self.payload_endpoints 116 | 117 | if remove_empty: 118 | if len(response['context']) < 1: 119 | response.pop('context') 120 | 121 | return response 122 | 123 | def set_payload(self, payload): 124 | self.event['payload'] = payload 125 | 126 | def set_payload_endpoint(self, payload_endpoints): 127 | self.payload_endpoints = payload_endpoints 128 | 129 | def set_payload_endpoints(self, payload_endpoints): 130 | if 'endpoints' not in self.event['payload']: 131 | self.event['payload']['endpoints'] = [] 132 | 133 | self.event['payload']['endpoints'] = payload_endpoints 134 | 135 | aws_dynamodb = boto3.client('dynamodb') 136 | 137 | 138 | def lambda_handler(request, context): 139 | 140 | # Dump the request for logging - check the CloudWatch logs 141 | print('lambda_handler request -----') 142 | print(json.dumps(request)) 143 | 144 | if context is not None: 145 | print('lambda_handler context -----') 146 | print(context) 147 | 148 | # Validate we have an Alexa directive 149 | if 'directive' not in request: 150 | aer = AlexaResponse( 151 | name='ErrorResponse', 152 | payload={'type': 'INVALID_DIRECTIVE', 153 | 'message': 'Missing key: directive, Is the request a valid Alexa Directive?'}) 154 | return send_response(aer.get()) 155 | 156 | # Check the payload version 157 | payload_version = request['directive']['header']['payloadVersion'] 158 | if payload_version != '3': 159 | aer = AlexaResponse( 160 | name='ErrorResponse', 161 | payload={'type': 'INTERNAL_ERROR', 162 | 'message': 'This skill only supports Smart Home API version 3'}) 163 | return send_response(aer.get()) 164 | 165 | # Crack open the request and see what is being requested 166 | name = request['directive']['header']['name'] 167 | namespace = request['directive']['header']['namespace'] 168 | 169 | # Handle the incoming request from Alexa based on the namespace 170 | 171 | if namespace == 'Alexa.Authorization': 172 | if name == 'AcceptGrant': 173 | # Note: This sample accepts any grant request 174 | # In your implementation you would use the code and token to get and store access tokens 175 | grant_code = request['directive']['payload']['grant']['code'] 176 | grantee_token = request['directive']['payload']['grantee']['token'] 177 | aar = AlexaResponse(namespace='Alexa.Authorization', name='AcceptGrant.Response') 178 | return send_response(aar.get()) 179 | 180 | if namespace == 'Alexa.Discovery': 181 | if name == 'Discover': 182 | adr = AlexaResponse(namespace='Alexa.Discovery', name='Discover.Response') 183 | capability_alexa = adr.create_payload_endpoint_capability() 184 | capability_alexa_powercontroller = adr.create_payload_endpoint_capability( 185 | interface='Alexa.PowerController', 186 | supported=[{'name': 'powerState'}]) 187 | adr.add_payload_endpoint( 188 | friendly_name='Sample Switch', 189 | endpoint_id='sample-switch-01', 190 | capabilities=[capability_alexa, capability_alexa_powercontroller]) 191 | return send_response(adr.get()) 192 | 193 | if namespace == 'Alexa.PowerController': 194 | # Note: This sample always returns a success response for either a request to TurnOff or TurnOn 195 | endpoint_id = request['directive']['endpoint']['endpointId'] 196 | power_state_value = 'OFF' if name == 'TurnOff' else 'ON' 197 | correlation_token = request['directive']['header']['correlationToken'] 198 | 199 | # Check for an error when setting the state 200 | state_set = set_device_state(endpoint_id=endpoint_id, state='powerState', value=power_state_value) 201 | if not state_set: 202 | return AlexaResponse( 203 | name='ErrorResponse', 204 | payload={'type': 'ENDPOINT_UNREACHABLE', 'message': 'Unable to reach endpoint database.'}).get() 205 | 206 | apcr = AlexaResponse(correlation_token=correlation_token) 207 | apcr.add_context_property(namespace='Alexa.PowerController', name='powerState', value=power_state_value) 208 | return send_response(apcr.get()) 209 | 210 | 211 | def send_response(response): 212 | # TODO Validate the response 213 | print('lambda_handler response -----') 214 | print(json.dumps(response)) 215 | return response 216 | 217 | 218 | def set_device_state(endpoint_id, state, value): 219 | attribute_key = state + 'Value' 220 | response = aws_dynamodb.update_item( 221 | TableName='SmartHome', 222 | Key={'ItemId': {'S': endpoint_id}}, 223 | AttributeUpdates={attribute_key: {'Action': 'PUT', 'Value': {'S': value}}}) 224 | print(response) 225 | if response['ResponseMetadata']['HTTPStatusCode'] == 200: 226 | return True 227 | else: 228 | return False 229 | -------------------------------------------------------------------------------- /Chapter7/Boto3 Setup.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Installing and upgrading `boto3`" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "!pip install boto3==1.0.0" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": { 23 | "scrolled": true 24 | }, 25 | "outputs": [], 26 | "source": [ 27 | "!pip install --upgrade boto3" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Loading up the necessary environment variables" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 4, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "import os\n", 44 | "\n", 45 | "aws_access_key_id= os.environ['aws_access_key_id']\n", 46 | "aws_secret_access_key = os.environ['aws_secret_access_key']" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "## Calling `boto3` to interact with Amazon s3 with your credentials" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 5, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "import boto3\n", 63 | "\n", 64 | "s3 = boto3.resource(\n", 65 | " 's3',\n", 66 | " aws_access_key_id=aws_access_key_id,\n", 67 | " aws_secret_access_key=aws_secret_access_key\n", 68 | ")" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "## Enlisting the bucket names" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 6, 81 | "metadata": {}, 82 | "outputs": [ 83 | { 84 | "name": "stdout", 85 | "output_type": "stream", 86 | "text": [ 87 | "demo-bucket-sayak\n" 88 | ] 89 | } 90 | ], 91 | "source": [ 92 | "for bucket in s3.buckets.all():\n", 93 | " print(bucket.name)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "## Uploading an image to your bucket" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 7, 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "data": { 110 | "text/plain": [ 111 | "s3.Object(bucket_name='demo-bucket-sayak', key='my_image.jpeg')" 112 | ] 113 | }, 114 | "execution_count": 7, 115 | "metadata": {}, 116 | "output_type": "execute_result" 117 | } 118 | ], 119 | "source": [ 120 | "data = open('my_image.jpeg', 'rb')\n", 121 | "s3.Bucket('demo-bucket-sayak').put_object(Key='my_image.jpeg', Body=data)" 122 | ] 123 | } 124 | ], 125 | "metadata": { 126 | "kernelspec": { 127 | "display_name": "Python 3", 128 | "language": "python", 129 | "name": "python3" 130 | }, 131 | "language_info": { 132 | "codemirror_mode": { 133 | "name": "ipython", 134 | "version": 3 135 | }, 136 | "file_extension": ".py", 137 | "mimetype": "text/x-python", 138 | "name": "python", 139 | "nbconvert_exporter": "python", 140 | "pygments_lexer": "ipython3", 141 | "version": "3.6.5" 142 | }, 143 | "latex_envs": { 144 | "LaTeX_envs_menu_present": true, 145 | "autoclose": false, 146 | "autocomplete": true, 147 | "bibliofile": "biblio.bib", 148 | "cite_by": "apalike", 149 | "current_citInitial": 1, 150 | "eqLabelWithNumbers": true, 151 | "eqNumInitial": 1, 152 | "hotkeys": { 153 | "equation": "Ctrl-E", 154 | "itemize": "Ctrl-I" 155 | }, 156 | "labels_anchors": false, 157 | "latex_user_defs": false, 158 | "report_style_numbering": false, 159 | "user_envs_cfg": false 160 | }, 161 | "toc": { 162 | "base_numbering": 1, 163 | "nav_menu": {}, 164 | "number_sections": true, 165 | "sideBar": true, 166 | "skip_h1_title": false, 167 | "title_cell": "Table of Contents", 168 | "title_sidebar": "Contents", 169 | "toc_cell": false, 170 | "toc_position": {}, 171 | "toc_section_display": true, 172 | "toc_window_display": false 173 | } 174 | }, 175 | "nbformat": 4, 176 | "nbformat_minor": 1 177 | } 178 | -------------------------------------------------------------------------------- /Chapter7/RekognitionExample/image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter7/RekognitionExample/image.jpg -------------------------------------------------------------------------------- /Chapter7/my_image.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter7/my_image.jpeg -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__init__.py -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/admin.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/admin.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/models.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/models.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/__pycache__/views.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/__pycache__/views.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | name = 'api' 6 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/migrations/__init__.py -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/migrations/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/api/migrations/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path 3 | 4 | from . import views 5 | 6 | urlpatterns = [ 7 | path('', views.indexView), 8 | path('predict', views.predictView), 9 | ] -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/api/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.http import HttpResponse, JsonResponse 3 | from django.template import loader 4 | 5 | import os 6 | from django.conf import settings 7 | 8 | import cntk as C 9 | from cntk.ops.functions import load_model 10 | 11 | from PIL import Image 12 | import numpy as np 13 | 14 | import re 15 | import base64 16 | import random 17 | import string 18 | 19 | def indexView(request): 20 | template = loader.get_template('api/index.html') 21 | context = {} 22 | return HttpResponse(template.render(context, request)) 23 | 24 | def convertImage(imgData1, filename): 25 | imgstr = re.search(r'base64,(.*)', str(imgData1)).group(1) 26 | img = base64.b64decode(imgstr) 27 | with open(filename+'.png', 'wb') as output: 28 | output.write(img) 29 | 30 | def predictView(request): 31 | 32 | model = load_model(os.path.join(settings.BASE_DIR, "data/myModel.model")) 33 | 34 | post_data = request.POST.items() 35 | 36 | pd = [p for p in post_data] 37 | 38 | imgData1 = pd[1][0].replace(" ", "+") 39 | 40 | imgData1 += "=" * ((4 - len(imgData1) % 4) % 4) 41 | 42 | filename = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)]) 43 | 44 | convertImage(imgData1, filename) 45 | 46 | image = Image.open(filename+'.png').convert('1') 47 | 48 | image.thumbnail((28,28), Image.ANTIALIAS) 49 | 50 | image_np = np.array(image.getdata()).astype(int) 51 | image_np_expanded = np.expand_dims(image_np, axis = 0) 52 | 53 | predicted_label_probs = model.eval({model.arguments[0]: image_np_expanded}) 54 | 55 | data = np.argmax(predicted_label_probs, axis=1) 56 | 57 | return JsonResponse({"data": str(data[0])}) -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__init__.py -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/settings.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/settings.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/urls.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/urls.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/wsgi.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/wsgi.cpython-36.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/__pycache__/wsgi.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/cntkdemo/__pycache__/wsgi.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for cntkdemo project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '$6*ta8f*4sm_m+b1yege4b7!qu)wzhfsc)!tw%coxqo7+_d+p*' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'api', 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'cntkdemo.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [os.path.join(BASE_DIR, 'templates')], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'cntkdemo.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | 123 | STATICFILES_DIRS = [ 124 | os.path.join(BASE_DIR, "static"), 125 | ] 126 | 127 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/urls.py: -------------------------------------------------------------------------------- 1 | """cntkdemo URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('', include('api.urls')), 21 | path('admin/', admin.site.urls), 22 | ] 23 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/cntkdemo/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for cntkdemo project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cntkdemo.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/data/myModel.model: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/data/myModel.model -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/CNTKDemo/db.sqlite3 -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cntkdemo.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/static/index.js: -------------------------------------------------------------------------------- 1 | (function() 2 | { 3 | var canvas = document.querySelector( "#canvas" ); 4 | var context = canvas.getContext( "2d" ); 5 | canvas.width = 350; 6 | canvas.height = 350; 7 | 8 | var Mouse = { x: 0, y: 0 }; 9 | var lastMouse = { x: 0, y: 0 }; 10 | context.fillStyle="black"; 11 | context.fillRect(0,0,canvas.width,canvas.height); 12 | context.color = "white"; 13 | context.lineWidth = 15; 14 | context.lineJoin = context.lineCap = 'round'; 15 | 16 | debug(); 17 | 18 | canvas.addEventListener( "mousemove", function( e ) 19 | { 20 | lastMouse.x = Mouse.x; 21 | lastMouse.y = Mouse.y; 22 | 23 | Mouse.x = e.pageX - this.offsetLeft; 24 | Mouse.y = e.pageY - this.offsetTop; 25 | 26 | }, false ); 27 | 28 | canvas.addEventListener( "mousedown", function( e ) 29 | { 30 | canvas.addEventListener( "mousemove", onPaint, false ); 31 | 32 | }, false ); 33 | 34 | canvas.addEventListener( "mouseup", function() 35 | { 36 | canvas.removeEventListener( "mousemove", onPaint, false ); 37 | 38 | }, false ); 39 | 40 | var onPaint = function() 41 | { 42 | context.lineWidth = context.lineWidth; 43 | context.lineJoin = "round"; 44 | context.lineCap = "round"; 45 | context.strokeStyle = context.color; 46 | 47 | context.beginPath(); 48 | context.moveTo( lastMouse.x, lastMouse.y ); 49 | context.lineTo( Mouse.x, Mouse.y ); 50 | context.closePath(); 51 | context.stroke(); 52 | }; 53 | 54 | function debug() 55 | { 56 | /* CLEAR BUTTON */ 57 | var clearButton = $( "#clearButton" ); 58 | 59 | clearButton.on( "click", function() 60 | { 61 | 62 | context.clearRect( 0, 0, 350, 350 ); 63 | context.fillStyle="black"; 64 | context.fillRect(0,0,canvas.width,canvas.height); 65 | 66 | }); 67 | 68 | /* LINE WIDTH */ 69 | 70 | var slider = document.getElementById("myRange"); 71 | var output = document.getElementById("sliderValue"); 72 | output.innerHTML = slider.value; 73 | 74 | slider.oninput = function() { 75 | output.innerHTML = this.value; 76 | context.lineWidth = $( this ).val(); 77 | } 78 | 79 | $( "#lineWidth" ).change(function() 80 | { 81 | context.lineWidth = $( this ).val(); 82 | }); 83 | } 84 | }()); -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/static/style.css: -------------------------------------------------------------------------------- 1 | /* Space out content a bit */ 2 | body { 3 | padding-top: 20px; 4 | padding-bottom: 20px; 5 | } 6 | 7 | /* Everything but the jumbotron gets side spacing for mobile first views */ 8 | .header, 9 | .footer { 10 | padding-right: 15px; 11 | padding-left: 15px; 12 | } 13 | 14 | /* Custom page header */ 15 | .header { 16 | padding-bottom: 20px; 17 | border-bottom: 1px solid #e5e5e5; 18 | } 19 | /* Make the masthead heading the same height as the navigation */ 20 | .header h3 { 21 | margin-top: 0; 22 | margin-bottom: 0; 23 | line-height: 40px; 24 | } 25 | 26 | .container-narrow > hr { 27 | margin: 30px 0; 28 | } 29 | 30 | /* Main marketing message and sign up button */ 31 | .jumbotron { 32 | text-align: center; 33 | border-bottom: 1px solid #e5e5e5; 34 | padding-top: 20px; 35 | padding-bottom: 20px; 36 | } 37 | 38 | .bodyDiv{ 39 | text-align: center; 40 | } 41 | 42 | @media screen and (min-width: 768px) { 43 | /* Remove the padding we set earlier */ 44 | .header, 45 | .footer { 46 | padding-right: 0; 47 | padding-left: 0; 48 | } 49 | /* Space out the masthead */ 50 | .header { 51 | margin-bottom: 30px; 52 | } 53 | /* Remove the bottom border on the jumbotron for visual effect */ 54 | .jumbotron { 55 | border-bottom: 0; 56 | } 57 | } 58 | 59 | @media screen and (max-width: 500px) { 60 | .slidecontainer{ 61 | display: none; 62 | } 63 | 64 | } 65 | 66 | .slidecontainer{ 67 | float: left; 68 | width: 30%; 69 | } 70 | 71 | .jumbotronHeading{ 72 | margin-bottom: 7vh; 73 | } 74 | 75 | .canvasDiv{ 76 | display: flow-root; 77 | text-align: center; 78 | } -------------------------------------------------------------------------------- /Chapter8/CNTKDemo/templates/api/index.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Doodle Guess 12 | 13 | 14 | 15 | 16 | 17 |
18 |
19 | 24 |

Number Guess

25 |
26 |
27 |

Draw inside this Box!

28 |
29 |

Drag the slider to change the line width.

30 | 31 |

Value:

32 |

33 |
34 |
35 | 36 |
37 |

38 | 39 | 40 |

41 |
42 |
43 |
44 | 45 |

Prediction Results

46 | 47 |

48 |
49 |
{% csrf_token %}
50 |
51 |

© 2019 · Anubhav Singh

52 |
53 |
54 | 55 | 56 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /Chapter8/Text Analytics API/Text Analytics API.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Imports" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 14, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import requests\n", 17 | "import os\n", 18 | "from pprint import pprint" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "### Assigning the necessary variables and body parameter" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 4, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "api_key = os.environ['text_api_key']" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 5, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "text_analytics_base_url = \\\n", 44 | "'https://eastus.api.cognitive.microsoft.com/text/analytics/v2.0'" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 6, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "language_api_url = text_analytics_base_url + \"/languages\"\n", 54 | "\n", 55 | "documents = { 'documents': [\n", 56 | " { 'id': '1', 'text': 'I want to attend NeurIPS someday and present a paper there.' }\n", 57 | "]}" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "### Assigning the header param, making a call to the _language detection_ API and showing the response" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": 15, 70 | "metadata": {}, 71 | "outputs": [ 72 | { 73 | "name": "stdout", 74 | "output_type": "stream", 75 | "text": [ 76 | "{'documents': [{'detectedLanguages': [{'iso6391Name': 'en',\n", 77 | " 'name': 'English',\n", 78 | " 'score': 1.0}],\n", 79 | " 'id': '1'}],\n", 80 | " 'errors': []}\n" 81 | ] 82 | } 83 | ], 84 | "source": [ 85 | "headers = {\"Ocp-Apim-Subscription-Key\": api_key}\n", 86 | "response = requests.post(language_api_url, headers=headers, json=documents)\n", 87 | "language = response.json()\n", 88 | "pprint(language)" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "### Making a call to the sentiment analysis API and showing the response" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 17, 101 | "metadata": {}, 102 | "outputs": [ 103 | { 104 | "name": "stdout", 105 | "output_type": "stream", 106 | "text": [ 107 | "{'documents': [{'id': '1', 'score': 0.17243406176567078}], 'errors': []}\n" 108 | ] 109 | } 110 | ], 111 | "source": [ 112 | "sentiment_api_url = text_analytics_base_url + \"/sentiment\"\n", 113 | "\n", 114 | "headers = {\"Ocp-Apim-Subscription-Key\": api_key}\n", 115 | "response = requests.post(sentiment_api_url, headers=headers, json=documents)\n", 116 | "sentiment = response.json()\n", 117 | "pprint(sentiment)" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "### Making a call to the phrase extraction API and showing the response" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": 19, 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "name": "stdout", 134 | "output_type": "stream", 135 | "text": [ 136 | "{'documents': [{'id': '1', 'keyPhrases': ['NeurIPS', 'paper']}], 'errors': []}\n" 137 | ] 138 | } 139 | ], 140 | "source": [ 141 | "key_phrase_api_url = text_analytics_base_url + \"/keyPhrases\"\n", 142 | "\n", 143 | "headers = {\"Ocp-Apim-Subscription-Key\": api_key}\n", 144 | "response = requests.post(key_phrase_api_url, headers=headers, json=documents)\n", 145 | "phrases = response.json()\n", 146 | "pprint(phrases)" 147 | ] 148 | } 149 | ], 150 | "metadata": { 151 | "kernelspec": { 152 | "display_name": "Python 3", 153 | "language": "python", 154 | "name": "python3" 155 | }, 156 | "language_info": { 157 | "codemirror_mode": { 158 | "name": "ipython", 159 | "version": 3 160 | }, 161 | "file_extension": ".py", 162 | "mimetype": "text/x-python", 163 | "name": "python", 164 | "nbconvert_exporter": "python", 165 | "pygments_lexer": "ipython3", 166 | "version": "3.6.5" 167 | }, 168 | "latex_envs": { 169 | "LaTeX_envs_menu_present": true, 170 | "autoclose": false, 171 | "autocomplete": true, 172 | "bibliofile": "biblio.bib", 173 | "cite_by": "apalike", 174 | "current_citInitial": 1, 175 | "eqLabelWithNumbers": true, 176 | "eqNumInitial": 1, 177 | "hotkeys": { 178 | "equation": "Ctrl-E", 179 | "itemize": "Ctrl-I" 180 | }, 181 | "labels_anchors": false, 182 | "latex_user_defs": false, 183 | "report_style_numbering": false, 184 | "user_envs_cfg": false 185 | }, 186 | "toc": { 187 | "base_numbering": 1, 188 | "nav_menu": {}, 189 | "number_sections": false, 190 | "sideBar": true, 191 | "skip_h1_title": false, 192 | "title_cell": "Table of Contents", 193 | "title_sidebar": "Contents", 194 | "toc_cell": false, 195 | "toc_position": {}, 196 | "toc_section_display": true, 197 | "toc_window_display": false 198 | } 199 | }, 200 | "nbformat": 4, 201 | "nbformat_minor": 2 202 | } 203 | -------------------------------------------------------------------------------- /Chapter8/sample_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter8/sample_image.jpg -------------------------------------------------------------------------------- /Chapter9/.ipynb_checkpoints/Untitled-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /Chapter9/api/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter9/api/.DS_Store -------------------------------------------------------------------------------- /Chapter9/api/main.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from sklearn.model_selection import train_test_split 4 | from nltk.corpus import stopwords 5 | from nltk.tokenize import WordPunctTokenizer 6 | from sklearn.feature_extraction.text import TfidfVectorizer 7 | from sklearn.feature_extraction.text import CountVectorizer 8 | from sklearn.linear_model import LogisticRegression 9 | from flask import Flask, request, render_template, make_response 10 | from flask_wtf import FlaskForm 11 | from wtforms import StringField, validators 12 | from wtforms.validators import DataRequired, Email 13 | import io 14 | from flask_restful import Resource, Api 15 | import string 16 | import re 17 | import pickle 18 | from flask_jsonpify import jsonpify 19 | 20 | DEBUG = True 21 | app = Flask(__name__) 22 | # app.config.from_object(__name__) 23 | app.config['SECRET_KEY'] = 'abcdefgh' 24 | api = Api(app) 25 | 26 | class TextFieldForm(FlaskForm): 27 | text = StringField('Document Content', validators=[validators.data_required()]) 28 | 29 | class Flask_Work(Resource): 30 | def __init__(self): 31 | self.stopwordSet = set(stopwords.words("english")) 32 | pass 33 | 34 | def cleanText(line): 35 | line = line.translate(string.punctuation) 36 | line = line.lower().split() 37 | 38 | line = [word for word in line if not word in self.stopwordSet and len(word) >= 3] 39 | line = " ".join(line) 40 | 41 | return re.sub(r"[^A-Za-z0-9^,!.\/'+-=]", " ", line) 42 | 43 | def get(self): 44 | headers = {'Content-Type': 'text/html'} 45 | return make_response(render_template('index.html'), 200, headers) 46 | 47 | def post(self): 48 | f = open('model.pkl', 'rb') 49 | P, Q, userid_vectorizer = pickle.load(f), pickle.load(f), pickle.load(f) 50 | sentence = request.form['search'] 51 | test_data = pd.DataFrame([sentence], columns=['Text']) 52 | test_data['Text'] = test_data['Text'].apply(self.cleanText) 53 | test_vectors = userid_vectorizer.transform(test_data['Text']) 54 | test_v_df = pd.DataFrame(test_vectors.toarray(), index=test_data.index, 55 | columns=userid_vectorizer.get_feature_names()) 56 | 57 | predicted_ratings = pd.DataFrame(np.dot(test_v_df.loc[0], Q.T), index=Q.index, columns=['Rating']) 58 | predictions = pd.DataFrame.sort_values(predicted_ratings, ['Rating'], ascending=[0])[:10] 59 | 60 | JSONP_data = jsonpify(predictions.to_json()) 61 | return JSONP_data 62 | 63 | # return make_response(render_template('index.html'), 200, JSONP_data) 64 | 65 | 66 | api.add_resource(Flask_Work, '/') 67 | 68 | 69 | if __name__ == '__main__': 70 | # Main() 71 | app.run(host='127.0.0.1', port=4000, debug=True) 72 | -------------------------------------------------------------------------------- /Chapter9/api/model.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Chapter9/api/model.pkl -------------------------------------------------------------------------------- /Chapter9/api/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | What's my Product? 5 | 6 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | 32 |
33 | 34 |
35 | 36 |
37 | 38 |
39 | 40 |
41 | 42 |
43 |
44 |
45 | 46 |
47 |
48 |
49 |
50 |
    51 | Type the name of a food product. 52 |
53 |
54 |
55 |
56 | 80 | -------------------------------------------------------------------------------- /Code for generating plots/plotting.py: -------------------------------------------------------------------------------- 1 | print(__doc__) 2 | 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | from sklearn.pipeline import Pipeline 6 | from sklearn.preprocessing import PolynomialFeatures 7 | from sklearn.linear_model import LinearRegression 8 | from sklearn.model_selection import cross_val_score 9 | 10 | 11 | def true_fun(X): 12 | return np.sin(1.5 * np.pi * X) 13 | 14 | np.random.seed(0) 15 | 16 | n_samples = 30 17 | degrees = [1, 2, 15] 18 | 19 | X = np.sort(np.random.rand(n_samples)) 20 | y = true_fun(X) + np.random.randn(n_samples) * 0.1 21 | 22 | plt.figure(figsize=(14, 5)) 23 | for i in range(len(degrees)): 24 | ax = plt.subplot(1, len(degrees), i + 1) 25 | plt.setp(ax, xticks=(), yticks=()) 26 | 27 | polynomial_features = PolynomialFeatures(degree=degrees[i], 28 | include_bias=False) 29 | linear_regression = LinearRegression() 30 | pipeline = Pipeline([("polynomial_features", polynomial_features), 31 | ("linear_regression", linear_regression)]) 32 | pipeline.fit(X[:, np.newaxis], y) 33 | 34 | # Evaluate the models using crossvalidation 35 | scores = cross_val_score(pipeline, X[:, np.newaxis], y, 36 | scoring="neg_mean_squared_error", cv=10) 37 | 38 | X_test = np.linspace(0, 1, 100) 39 | plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") 40 | plt.plot(X_test, true_fun(X_test), label="True function") 41 | plt.scatter(X, y, edgecolor='b', s=20, label="Samples") 42 | plt.xlabel("x") 43 | plt.ylabel("y") 44 | plt.xlim((0, 1)) 45 | plt.ylim((-2, 2)) 46 | plt.legend(loc="best") 47 | # plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( 48 | # degrees[i], -scores.mean(), scores.std())) 49 | plt.show() 50 | -------------------------------------------------------------------------------- /Excel/Convolutions.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Excel/Convolutions.xlsx -------------------------------------------------------------------------------- /Excel/RNNs.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Excel/RNNs.xlsx -------------------------------------------------------------------------------- /Excel/Toy Dataset.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Hands-On-Python-Deep-Learning-for-Web/1aa7ddbda40af4890c8006dcec0225adb4f0a66f/Excel/Toy Dataset.xlsx -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | # Hands-On Python Deep Learning for Web 6 | 7 | 8 | Hands-On Python Deep Learning for Web 9 | 10 | This is the code repository for [Hands-On Python Deep Learning for Web](https://www.packtpub.com/data/hands-on-python-deep-learning-for-web?utm_source=github&utm_medium=repository&utm_campaign=9781789956085) by Anubhav Singh and Sayak Paul, published by Packt. 11 | 12 | **Integrating neural network architectures to build smart web apps with Flask, Django, and TensorFlow** 13 | 14 | ## What is this book about? 15 | When used effectively, deep learning techniques can help you develop intelligent web apps. In this book, you'll cover the latest tools and technological practices that are being used to implement deep learning in web development using Python. 16 | Starting with the fundamentals of machine learning, you'll focus on DL and the basics of neural networks, including common variants such as convolutional neural networks (CNNs). You'll learn how to integrate them into websites with the frontends of different standard web tech stacks. The book then helps you gain practical experience of developing a deep learning-enabled web app using Python libraries such as Django and Flask by creating RESTful APIs for custom models. Later, you'll explore how to set up a cloud environment for deep learning-based web deployments on Google Cloud and Amazon Web Services (AWS). 17 | 18 | This book covers the following exciting features: 19 | * Explore deep learning models and implement them in your browser 20 | * Design a smart web-based client using Django and Flask 21 | * Work with different Python-based APIs for performing deep learning tasks 22 | * Implement popular neural network models with TensorFlow.js 23 | * Design and build deep web services on the cloud using deep learning 24 | 25 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1789956080) today! 26 | 27 | https://www.packtpub.com/ 28 | 29 | ## Instructions and Navigations 30 | All of the code is organized into folders. For example, Chapter02. 31 | 32 | The code will look like the following: 33 | ``` 34 | if (test expression) 35 | { 36 | Statement upon condition is true 37 | } 38 | ``` 39 | 40 | **Following is what you need for this book:** 41 | This deep learning book is for data scientists, machine learning practitioners, and deep learning engineers who are looking to perform deep learning techniques and methodologies on the web. You will also find this book useful if you’re a web developer who wants to implement smart techniques in the browser to make it more interactive. Working knowledge of the Python programming language and basic machine learning techniques will be beneficial. 42 | 43 | With the following software and hardware list you can run all code files present in the book (Chapter 1-12). 44 | 45 | ### Software and Hardware List 46 | 47 | | Chapter | Software required | OS required | 48 | | -------- | ---------------------------------------------------------- | --------------------------------------------------- | 49 | | 1-12 | Anaconda distribution of Python and other Python packages | 1 GB RAM minimum, 8 GB recommended 15 GB disk space | 50 | | 1-12 | Code editor of your choice (Sublime Text 3 recommended) | 2 GB RAM | 51 | 52 | 53 | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](http://www.packtpub.com/sites/default/files/downloads/9781789956085_ColorImages.pdf). 54 | 55 | 56 | ### Related products 57 | * Hands-On Machine Learning with TensorFlow.js [[Packt]](https://www.packtpub.com/data/hands-on-machine-learning-with-tensorflow-js?utm_source=github&utm_medium=repository&utm_campaign=9781838821739) [[Amazon]](https://www.amazon.com/dp/1838821732) 58 | 59 | * Hands-On Web Scraping with Python [[Packt]](https://www.packtpub.com/big-data-and-business-intelligence/hands-web-scraping-python?utm_source=github&utm_medium=repository&utm_campaign=9781789533392) [[Amazon]](https://www.amazon.com/dp/1789533392) 60 | 61 | ## Get to Know the Authors 62 | 63 | **Anubhav Singh**, a web developer since before Bootstrap was launched, is an explorer of technologies, often pulling off crazy combinations of uncommon tech. An international rank holder in the Cyber Olympiad, he started off by developing his own social network and search engine as his first projects at the age of 15, which stood among the top 500 websites of India during their operational years. He's continuously developing software for the community in domains with roads less walked on. You can often catch him guiding students on how to approach ML or the web, or both together. He's also the founder of The Code Foundation, an AI-focused start-up. Anubhav is a Venkat Panchapakesan Memorial Scholarship awardee and an Intel Software Innovator. 64 | 65 | 66 | **Sayak Paul** is currently with PyImageSearch, where he applies deep learning to solve real-world problems in computer vision and bring solutions to edge devices. He is responsible for providing Q&A support to PyImageSearch readers. His areas of interest include computer vision, generative modeling, and more. Previously at DataCamp, Sayak developed projects and practice pools. Prior to DataCamp, Sayak worked at TCS Research and Innovation (TRDDC) on data privacy. There, he was a part of TCS's critically acclaimed GDPR solution called Crystal Ball. Outside of work, Sayak loves to write technical articles and speak at developer meetups and conferences. 67 | 68 | 69 | ## Other books by the authors 70 | * [Mobile Deep Learning with TensorFlow Lite, ML Kit and Flutter](https://www.packtpub.com/data/mobile-deep-learning-projects?utm_source=github&utm_medium=repository&utm_campaign=9781789611212) 71 | 72 | 73 | ### Suggestions and Feedback 74 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSdy7dATC6QmEL81FIUuymZ0Wy9vH1jHkvpY57OiMeKGqib_Ow/viewform) if you have any feedback or suggestions. 75 | ### Download a free PDF 76 | 77 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
78 |

https://packt.link/free-ebook/9781789956085

-------------------------------------------------------------------------------- /XMLs for figures/Big Picture of AI, ML and DL.xml: -------------------------------------------------------------------------------- 1 | 2 | 7ZY9k5swEIZ/DWUyQgJsl7bvkjRXuUitwBo0ERKR5YDz67MY8SFjz1zBeK64Cund1cc+78IQsH3ZfDe8Kt50BjKgJGsC9hJQGoYkwUerXDol3mw6ITcic0mjcBD/wInEqWeRwclLtFpLKypfTLVSkFpP48bo2k87aumfWvEcZsIh5XKu/hSZLTp1HZNR/wEiL+xQsIuUvE92wqngma4nEnsN2N5obbtR2exBtvB6Lt26bw+iw8UMKPueBbRb8JfLs6vN3cte+mJxAXLFya4uhIVDxdM2UqO1qBW2lDgLcei2AmOheXidcCgSuwN0CdZcMKVfsKJf425R3xoOVD1yjolLKSaMo8glcudtPmw+lo8DR+A+DfaxaNAN8VgMbTSBwXpAUxiMLQAj+lgwWMR8GEk8g0GT9RwGJQvAiO/ASCSesPuFg9xea+yEo8aCppiSP2fdB76crh+zLSaEUdWMwX6XrbHiKFLBr6cr2yLOQSFXtz3etDvBPxXlyU1ufELq1jfkZI3+DXsttUFFadWaeBRS3kgcT1c4TdElQH3XeijwS7h1gVJkmXzUAUafVQYtQrJQE8T+G7GavxDh3RdigRZIntUCbzwtBNKnRAI3Sqj80/vWw/XN15A+0fzVs8x/Aag+nfedj4jv/L2fgqWcx+n493WNTf5h2et/ -------------------------------------------------------------------------------- /XMLs for figures/NeuralNetworkAnatomy (2).xml: -------------------------------------------------------------------------------- 1 | 5VpLt5owEP41LvWQBFCXamu76OOecxd97FLIlbRAOCFW7a/vIAkKXCuXomjrRjJMJmG+eRIGZBFt30iaBO+Fz8IBtvztgLwaYIyQ5cJfRtnlFMexcsJKcl8zHQiP/BfTRMO25j5LS4xKiFDxpEz0RBwzT5VoVEqxKbM9ibC8akJXrEZ49GhYp37ivgpy6gSPD/S3jK8CszJyp/mdiBpm/SRpQH2xOSKR1wOykEKo/CraLliYKc/oJZ+3PHG32JhksWoyYb6bf334GCjnw3KNfy2G4SzaDLWUnzRc6wfWm1U7owGQAsqGwXwTcMUeE+pldzaAN9ACFYUwQnBJ0yRH4IlvGSw617KZVGx7ctOoUAXYEBMRU3IHLGbCRGtvZ8xCjzcHMFxNCo5wMDSq4V8Vkg8aggutpBcoDN+bwiY9K4zcmcLwuGeF2Q0UFvuzLLbByAtpmnKvrKd8AvNroe2sUo4e2nnmoQ1NspAq/rMs/jlN6BUeBIeFC53bFZUjpywhFWvpMT3pOKRV5NSwQ/aoIkpRuWKqJgrUR3dHbEnGkJ7e8emVDlDnMg/AF2ptbwvOf2gLuBtbQKQi6IQldAWV+/dQASBy9xkGlhl8yQZgaGT+fR0lj1oUld4LgIWCaf/k52L0rRgAtloawPiMoAsbwPi8AUAJmGSXPNpXncfYZzmMQ9k5C/kqBpoSyRH1Hf3GwgeRcsVFdvebUEpEwBBmN+bU+7GSYh37CxEKuV+LPO1/wLJfbGYyp/VcGtX7eRUolZXVs0w3eOn5sT3iUFg/8dhncuTBinjpU0XhL6NDvFyyNAVz4zQc0iTJqqMlAk9YSuYJ6Q/3mxp6XHohG/pCDRGejJJ41UHeJtW4UU/b6BmjRZdK20bwzRY6eDotB0g8rWnsqoUOuvXmg1gVG3N6Lg1NbvyrJLPl6vPR9SHFwEz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PxPw== -------------------------------------------------------------------------------- /XMLs for figures/RNN Unrolled (1).xml: -------------------------------------------------------------------------------- 1 | 7XxXk+RGru6v0eM5QW8e6W3Rs0jWG703RU/++ktOz0ia0eyutCt3N05HRzcJZiKTABL4gMyqH2Cm3YUxHIpHn6TNDxCQ7D/A7A8QBIIAdv27KccHBUWBD0I+lsnnRj8R7PJMPxO/NFvKJJ2+ajj3fTOXw9fEuO+6NJ6/ooXj2G9fN8v65utRhzBPf0Gw47D5JdUrk7n4oBIQ/hNdTMu8+DIyiJEfT9rwS+PPbzIVYdJvPyPB3A8wM/b9/HHV7kza3ML7IpePfvw/ePrjxMa0m39NB02nD0RhCF3GJ9o/obklhf8BP892DZvl8xt/nu18fBFBmlwS+Xzbj3PR530XNtxPVHrsly5J73GA666Y2+a6BK/LKp3n47NSw2XuL9JPHNS+Hz63m+axr38U8CUa+mMW99D/8HU/k6Z+GeP0n73jZ7MJxzyd/1k7+EetXOac9m06j8fVcUybcC7XrycSfrar/Md2P4n+uvgs/d+iie8oAmuu+dLRdZHPn2TyQcj6SwQ/VxH2XvovD/5n+iRu6moAwsP+08MvXKgvbK5pfnD6mvtF/tmI39jCT5q+1bYV5ZzaQ/hJ/NvlAL7WflY2DdM3/fipL5yCCZriP2r7Z09IDIdD7Mfx1nSc0/2f6/2XavrcAcY+r7fPDgcCPt9vPy1f8jOp+NnKRYA/SLHQP1Psv6vE/QuPaRm+0MCfafBn5N+oV+A36zXLUiyOv6fXBCcjAPi99Er8L/q1ZvFfahaH/0TNon+EZo+/kWav9UokyPc0S0ARjP1uK/ZbzYLwX6xZ/FdExS6hbnxx3cVNOE1l/LUo072c/Vvq17t93AWfdfA7hjbo14a27yvgZ+JFv+MSv9B+dQD8PILRl58C1Bf9Et94ZPwbtX285udeP0cw3zBC4G8YQd8w+pDDLxh9MoEfX/s/CNHfc+V/uln8VWpEAOT7gfU3q/EbRuC39vBHqxH+P6j1uzhuFPibQS0Q+UOx1tfq+i18gf8lYPi7zL8T7aG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W8YTbk1DPO0s/AhvuVpR5BdjDb6SFEKQ9rR2IBc8cA4oniL5Yiy807pxoxVgaQLGTuwhMvl8Ao+4CAmzZQCWAyWnyDFDghdrK8d6FXM2+e4VBc1cn1ERop/FQKFn03zBtv5q+NHXnybXA+8Am6fIVJFMmzVC613pHZiAMj1XqqTpJx5iXW6+UKVRz7cge1fen3VtAkSGvle/d0xK2hlEhypyxQGze3PYVSjVbg5Y8K9MyMkqBZcJcW5QdhO1CKhXdgP2L8q/I2MihN5euxLMrttwAtbcb7ILL1jNxGQqmgsRU4nINHvd+La7z0qKX7Ha/Pg4P8Hyqu+3eB0EoruGd2l7MlmF+nyN833zMFwSBLyf6fnYwCcTRX55Mgr58n8nvfoYP/t5HC//BGZ+sSffPZ7bof3V86/c83f/nHNv6Vj3/9ocA4G8/Pvq7nb67y1Q/fq/OR/Ofvp0I5v4f -------------------------------------------------------------------------------- /XMLs for figures/training-error-gen-error.xml: -------------------------------------------------------------------------------- 1 | 7VjLbuIwFP0aloySGEJYFtrpSDMjjcQ8V5Ubm8StianjQOjXz01i5wmir1BV7Yr42D627zk312GA5qv0UuJ1+F0QygeORdIBOh84jm1bLvxkyK5AxmOrAALJiB5UAQt2TzVohiWM0LgxUAnBFVs3QV9EEfVVA8NSim1z2FLw5qprHNAOsPAx76J/GFFhgXrOpMK/UBaEZmXbnRY9K2wG65PEISZiW4PQxQDNpRCqeFqlc8qz4Jm4FPM+H+gtNyZppB4y4e7u19V9bN8u0Nz6Pvl6dTOUeKhZNpgn+sB6s2pnIkAjcpYFElo+x3HM/AGahWrFAbDhMVZS3JbBgWPNCgpKOpGttmqXAQDnULGiSu5gyLYKsfFJWIuuwSTlWLFNkx5rpYOSrlzhh2CwsGMZVxpJtCeRZTUpYpFIn+pZ9ZAeIbJHLSKFZUBVhwgeaseuoFyxR6jnfKj3DPUQOkLUs3qoD/WWjPO54ELmBGjp+dT3y5G1nmtvPAJF0MxP5IYSTfhuxHfcVup6pxV/tEd8l0OwZtfwEKhciwJYinzjlS3cu0SYjmGcl8wzGGCjdVp1GpafErOIRUEmK1hJGlbYdUHcXAzg2gZadlQ0VfsMaGwViYi2PKghzFkQZS4GG1HAZxsqFYMye6Y7VoyQbJnZNmSKLtbYz9bcwqUCMCmSiOQetcptZQQ0faxLzQT3gI1qLrbRHhs71mHHNizyWD9MurkPSbjQTSFVKAIRYX5Roc3MrYlCU6b+ZsH6NNatf7We81THMW/sdOOGKrXT1y+cKAFQteg3IdbPrhdwuDw3jydFkXrHxnXFffC75VlKeafK3BmDvb/5bJVCgSgimzWcvlD6jprZW2blq2Xv9D1exEau25RhOoUXzpOqcZvKRh2qnuux+d78kPCJErqTo1R9S9jLx2zrQk3G1COjfRdqz7lGEM43dqF+SQdYrSSenNwB+z6Ie6nNlzSiEsrkfVHbPu7WlQ3G1kFHvVp9tk/2ufUbS4YjCPCbt0IfFzfktbxh9+kNaFZ/rxbvmOpPanTxHw== -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman --------------------------------------------------------------------------------