Camera permission dialogue box not appearing - javascript

So I've been trying to make a UI in which the user can upload his pictures to local system (To move from one location to images database by opening a file manager dialogue box) or take live pictures and add to the images database. I made this simple html file which is running well but after i try to run it with flask after creating a localhost , google chrome doesn't prompt for camera permission from above and somehow the permission is already granted but the camera doesn't work . Here is the code- app.py
import os
from flask import Flask, request, render_template, send_from_directory
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route("/")
def index():
return render_template("upload.html")
#app.route("/upload", methods=["POST"])
#for the intake of the folder name that needs to be created or selected in the dataset folder
def upload():
fold_nam=request.form["name"]
folder_name = request.form.get('superhero')
'''
# this is to verify that folder to upload to exists.
if os.path.isdir(os.path.join(APP_ROOT, 'files/{}'.format(folder_name))):
print("folder exist")
'''
#Change this target variable as per the device working in (set your own path address of the dataset folder)
target="/home" + str(fold_nam).lower()
print(target)
if not os.path.isdir(target):
os.mkdir(target)
print(request.files.getlist("file"))
for upload in request.files.getlist("file"):
print(upload)
print("{} is the file name".format(upload.filename))
filename = upload.filename
# This is to verify files are supported
ext = os.path.splitext(filename)[1]
if (ext == ".jpg") or (ext == ".png"):
print("File supported moving on...")
else:
render_template("Error.html", message="Files uploaded are not supported...")
destination = "/".join([target, filename])
print("Accept incoming file:", filename)
print("Save it to:", destination)
upload.save(destination)
# return send_from_directory("images", filename, as_attachment=True)
return render_template("complete.html", image_name=filename)
if __name__ == "__main__":
app.run(port=4555, debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="frm1" action="/action_page.php">
Name: <input type="text" name="fname"><br>
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
<script type="text/javascript">
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
});
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
</script>
</form>
<div class="container">
<video id="video" width="300" height="300" autoplay="true"></video>
<button class="button" id="snap">Photo</button>
<canvas id="canvas" width="300" height="300"></canvas>
<br>
<a id="download" href="/images/myw3schoolsimage.jpg" download>download</a>
<div>
<input type="submit" value="Upload!" id="upload-button"><br>
</body>
<script>
$("#file-picker").change(function () {
var input = document.getElementById('file-picker');
for (var i = 0; i < input.files.length;i++) {
//koala.jpg, koala.JPG substring(index) lastIndexOf('a') koala.1.jpg
var ext = input.files[i].name.substring(input.files[i].name.lastIndexOf('.') + 1).toLowerCase()
if((ext == 'jpg') || (ext == 'png')) {
$("#msg").text("Files are supported")
}
else {
$("#msg").text("Files are NOT supported")
document.getElementById("file-picker").value = "";
}
}
});
</script>
<script src="./index.js"></script>
</html>
index.js
(() => {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = document.getElementById("img")
var download = document.getElementById("download")
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
video.srcObject = stream;
video.play();
});
}
document.getElementById("snap").addEventListener("click", () => {
context.drawImage(video, 0, 0, 300, 300);
img.setAttribute("src", canvas.toDataURL("image/png"))
download.setAttribute("href", canvas.toDataURL("image/png"))
});
})()
All i want is to run the **index.html ** using flask with the camera running properly in localhost.
I know that my code is not in the finished state , but i'm stuck at this very place. I would like to mention that all my files are in proper directories and i have no indentation errors etc. Anyone who is willing to help is requested to mention every minute detail as I'm not very good at this .
Thankyou!

Related

Failed to load resource: the server responded with a status of 404 (NOT FOUND) np4A8.png:1

I have two files to make a CAPTCHA page, here's the HTML file
<!DOCTYPE HTML>
<html>
<head>
<title> Example </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<link rel="shortcut icon" href="#">
</head>
<body onload="example()">
<h1> Captcha Example </h1>
<div id="x"></div>
<label> Enter the text from Captcha above </label>
<input type="text" id="CaptchaInput">
<br> <br>
<input type="button" value="Enter" id="Button">
<script>
var Captcha ='{{ newData.CaptchaValue }}';
Button.addEventListener("click", function() {
if(Input === Captcha) {
console.log("Match");
} else {
console.log("Incorrect");
}
})
function example () {
$.ajax({
url: "/",
context: document.body
})
var img1 = new Image();
img1.src = "../np4A8.png";
}
</script>
</body>
</html>
And my Python file
import random
from flask import Flask, render_template
from captcha.image import ImageCaptcha
app = Flask(__name__)
result_str = ''.join(
(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') for i in range(5)))
#app.route('/')
def generateCaptcha():
# Create an image instance of the given size
image = ImageCaptcha(width=280, height=90)
# Image captcha text will equal random result
captcha_text = result_str
# generate the image of the given text
data = image.generate(captcha_text)
# write the image on the given file and save it
image.write(captcha_text, result_str + '.png')
newData = {'CaptchaValue': result_str}
return render_template('main.html', newData=newData)
if __name__ == "__main__":
app.run(debug=True)
I always get the error:
Failed to load resource: the server responded with a status of 404 (NOT FOUND) np4A8.png:1
I need to change it to the captcha file name but first I wanted to work with an image that already exists. Basically I have the main directory and a templates folder with my HTML page. The main directory folder has the PNG images. I thought "../np4A8.png" was the previous directory and looking for a photo called np4A8.png. Please help me. I'm so close to finishing and been struggling with this

upload image from static folder in flask python without reloading the html page

I want to make a flask app where i will select an image from local computer and then store it in static folder and then show the image on the same html page without loading the page again.how can i do this.
this is app.py file
from flask import Flask, request, render_template, send_from_directory,session
import os
from os import listdir
from os.path import isfile, join
import random
import pandas as pd
import numpy as np
from skimage.io import imread, imshow, concatenate_images
from skimage.transform import resize
from skimage.morphology import label
from keras.models import Model, load_model
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
__author__ = 'ibininja'
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route("/")
def index():
return render_template("upload.html")
#app.route("/upload",methods=["POST"])
def upload():
target = os.path.join(APP_ROOT, 'static/')
print(target)
print(request.files.getlist("file"))
for upload in request.files.getlist("file"):
print(upload)
print("{} is the file name".format(upload.filename))
filename = upload.filename
destination = "/".join([target, filename])
print("Accept incoming file:", filename)
print("Save it to:", destination)
upload.save(destination)
session['store']=filename
return render_template("upload.html",image_name=filename)
#app.route("/denoise")
def denoise():
s=session.get('store')
return s
if __name__ == "__main__":
app.secret_key = '123027'
app.config['memcache'] = 'filesystem'
app.run(port=4555,debug=True)
this is upload.html file
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<strong>Files:</strong><br>
<input id="file-picker" type="file" name="file" accept="image/*" multiple>
<div id="msg"></div>
<input type="submit" value="Upload!" id=".showbtn">
<img src= "{{url_for('static',filename=image_name)}}" height="250" width="250"
alt="show image here" class="img-responsive img-thumbnail"/>
</form>
<div>
<form action="/denoise" >
<input type="submit" value="Denoise">
</form>
</div>
</body>
<script>
$("#file-picker").change(function(){
var input = document.getElementById('file-picker');
for (var i=0; i<input.files.length; i++)
{
//koala.jpg, koala.JPG substring(index) lastIndexOf('a') koala.1.jpg
var ext= input.files[i].name.substring(input.files[i].name.lastIndexOf('.')+1).toLowerCase()
if ((ext == 'jpg') || (ext == 'png')||(ext == 'jpeg'))
{
$("#msg").text("Files are supported")
}
else
{
$("#msg").text("Files are NOT supported")
document.getElementById("file-picker").value ="";
}
}
} );
</script>
</html>
I want the output like this
before file upoad
after file upload
Basically something like:
var image = document.querySelector('#upload-form img');
image.src = image.src + '?time=' + new Date().getTime();
Depending if your image URL has already a query string then you would have to handle that, so it could be:
image.src = image.src + '&time=' + new Date().getTime();

How to implement custom Tensorflow.js models into webpage?

I would like to create a website that can classify different types of cars. I have managed to get the website working to use the mobile net model, but I would like to use a custom model that I trained in google colab and then converted into javascript. Does anyone know how I could achieve this?
Here is the javascript code:
// Defining Variables
const webcamElement = document.getElementById('webcam');
let net;
var webcamrunning = false; // Flag, indicates if webcam-prediction is running or not
var bw = document.getElementById('butwebcam')
var bi = document.getElementById('butimage')
// App that predicts image
async function app() {
console.log('Loading mobilenet..');
const uploadJSONInput = document.getElementById('upload-json');
const model = await tf.loadLayersModel(tf.io.browserFiles([uploadJSONInput.files[0]]));
// Check if model loaded, if not, load it.
if (net == undefined)
{bi.innerHTML = 'Wait for Initiation...';
net = await model.load();
console.log('Sucessfully loaded model');
bi.innerHTML = 'Predict'}
else {console.log('Model already loaded')};
// Make a prediction through the model on our image.
const imgEl = document.getElementById('output');
const result = await net.classify(imgEl);
document.getElementById('console_pic').innerText =
`Prediction: ${result[0].className}
Probability: ${Math.round(result[0].probability*100)} %
`;
}
// Function that activates (starts webcam app) and deactivates the Webcam-Prediction
function start_webcam(){
if (webcamrunning == false)
{app_webcam();
}
else {webcamrunning = false;
bw.innerHTML = 'Activate Predicting';
};
};
// Setup Webcam
async function setupWebcam() {
return new Promise((resolve, reject) => {
const navigatorAny = navigator;
navigator.getUserMedia = navigator.getUserMedia ||
navigatorAny.webkitGetUserMedia || navigatorAny.mozGetUserMedia ||
navigatorAny.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true},
stream => {
webcamElement.srcObject = stream;
webcamElement.addEventListener('loadeddata', () => resolve(), false);
},
error => reject());
} else {
reject();
}
});
}
// Webcam application
async function app_webcam() {
console.log('Loading mobilenet..');
// Check if model loaded, if not, load it.
if (net == undefined)
{bw.innerHTML = 'Wait for Initiation...';
net = await mobilenet.load();
console.log('Sucessfully loaded model');}
else {console.log('Model already loaded')};
await setupWebcam();
webcamrunning =true;
bw.innerHTML = 'Stop Predicting';
while (webcamrunning) {
const result = await net.classify(webcamElement);
document.getElementById('console_vid').innerText =
`Prediction: ${result[0].className}
Probability: ${Math.round(result[0].probability*100)} %
`;
// Give some breathing room by waiting for the next animation frame to
// fire.
await tf.nextFrame();
}
}
;
Here is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel='stylesheet' href='styles.css'/>
<input type="file" id="upload-json" src="C:\Users\USER\Desktop\ImageClassifier-master\model\model.json"/>
<!-- Load the latest version of TensorFlow.js -->
<script src="https://unpkg.com/#tensorflow/tfjs"></script>
<script src="https://unpkg.com/#tensorflow-models/mobilenet"></script>
<title> Image Classifier with MobileNet </title>
</head>
<body>
<img style='margin-top: -6px; z-index: 19;' id="header" height ="320">
<h1 style='margin-top: -35px'> What car is that?</h1>
<br>
<hr/>
<br>
<em> <strong> </strong> </em>
<br>
<br>
<hr/>
<br>
<h2> Upload your own Picture</h2>
<!-- Upload Function with File Preview -->
<input type="file" accept=".png, .jpg, .jpeg" height="200"
onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">
<!-- Predict button, calls predict function in Javascript -->
<button id="butimage" onclick="app()"> Predict! </button>
<!-- Window for Picture Preview -->
<div class = "window">
<span class="helper"></span>
<img class="center" id="output" alt="your image" src = "img/example.jpg" />
</div>
<div class = "result" id="console_pic">Result</div>
<br>
<hr/>
<br>
<br>
<br>
<br>
<script src="index.js"></script>
</body>
</html>

Error 400 in Flask "The browser (or proxy) sent a request that this server could not understand."

So, I am trying to follow this tutorial https://www.youtube.com/watch?v=eCz_DTtUBfo
about flask usage with my ML model. The part of loading the model works, but when I try to initialize it, it just doesn't work. Maybe I have some error in my writing.
I hope anyone could help me :c
Here is my Flask code:
from keras.preprocessing.image import img_to_array
from flask import request
from flask import jsonify
from flask import Flask
app = Flask(__name__)
def get_model():
global model
model = load_model('pecuscope_model.h5')
print(" * Model loaded!")
def preprocess_image(image, target_size):
if image.mode != "RGB":
image = image.convert("RGB")
image = image.resize(target_size)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
return image
print(" * Loading Keras model...")
get_model()
#app.route("/predict", methods=["GET","POST"])
def predict():
message = request.get_json(force=True)
encoded = message['image']
decoded = base64.b64decode(encoded)
image = Image.open(io.BytesIO(decoded))
processed_image = preprocess_image(image, target_size=(229, 229))
prediction = model.predict(processed_image).tolist()
response = {
'prediction': {
'mosquito': prediction[0][0],
'abeja': prediction[0][1]
}
}
return jsonify(response)
and my html:
<!DOCTYPE html>
<html>
<head>
<title>PecuScope Prediction</title>
<style>
* {
font-size:30px;
}
</style>
</head>
<body>
<input id="image-selector" type="file">
<button id="predict-button">Predict</button>
<p style="font-weight:bold">Predictions</p>
<p>Mosquito: <span id="mosquito-prediction"></span></p>
<p>Abeja: <span id=abeja-prediction"></span></p>
<img id="selected-image" src=""/>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
let base64Image;
$("#image-selector").change(function() {
let reader = new FileReader();
reader.onload = function(e) {
let dataURL = reader.result;
$('#selected-image').attr("src", dataURL);
base64Image = dataURL.replace("data:image/jpg;base64,","");
console.log(base64Image);
}
reader.readAsDataURL($("#image-selector")[0].files[0]);
$("#mosquito-prediction").text("");
$("#abeja-prediction").text("");
});
$("#predict-button").click(function(event){
let message = {
image: base64Image
}
console.log(message);
$.post("http://10.142.0.2:5000/predict", JSON.stringify(message),
function(response){
$("#mosquito-prediction").text(response.prediction.mosquito.toFixed(6));
$("#abeja-prediction").text(response.prediction.abeja.toFixed(6));
console.log(response);
});
});
</script>
<body>
<html>
I thought that could be a problem with indentation, or with spaces, I don't know. I'm very disappointed with myself. I can't follow a tutorial :c
Dunno if it's the reason, but at least you forgot " at html file body:
Abeja: span id=abeja-prediction"

create text file using javascript

I want to create text file (notepad type file) using javascript. My code is given below but it is not working plz. Suggest me any solution for creating text file.
var txt = new ActiveXObject("Scripting.FileSystemObject");
var s = txt.CreateTextFile("D:\\test.txt", true);// means file is store in my D drive.
s.WriteLine('Hello');
s.Close(); `
you can try this:
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
Also you can show this DEMO
The following code snippet demonstrate create a text files using the jQuery and HTML5 file API. For the sake of simplicity, in this example I am using Bootstrap CSS framework for building the page.
$('#btnSave').click(function() {
if ('Blob' in window) {
var fileName = prompt('Please enter file name to save', 'Untitled.txt');
if (fileName) {
var textToWrite = $('#exampleTextarea').val().replace(/n/g, 'rn');
var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
if ('msSaveOrOpenBlob' in navigator) {
navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
var downloadLink = document.createElement('a');
downloadLink.download = fileName;
downloadLink.innerHTML = 'Download File';
if ('webkitURL' in window) {
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.click(function(){
document.body.removeChild(event.target);
});
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
}
} else {
alert('Your browser does not support the HTML5 Blob.');
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Your HTML, CSS, and JavaScript playground.">
<title>HTML, CSS, JS Playground</title>
<meta content="width=device-width, initialscale=1" name="viewport">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" type="text/javascript"></script>
<script>
$(document ).ready(function() {
//Put your java script here
});
</script>
</head>
<body>
<div class="container">
<h1>Reading and Creating Text Files Using the HTML5 File API and jQuery</h1>
<div class="form-group">
<button type="button" class="btn btn-default" id="btnOpen">Open...</button>
<button type="button" class="btn btn-default" id="btnSave">Save</button>
</div>
<input type="file" id="exampleInputFile" accept=".txt,.csv,.xml" class="hidden">
<div class="form-group">
<textarea class="form-control" rows="15" id="exampleTextarea"></textarea>
</div>
</div>
</body>
source

Categories