i need to get image from url(request.args.get) and upload the same image to server using python Flask.
from flask import *
app = Flask(__name__)
#app.route('/success')
def success():
IMAGE= request.args.get('image')
image=cv2.imread(IMAGE)
ksize=(12,10)
image = cv2.blur(image, ksize)
cv2.imwrite(r"C:\Users\SiddanthShaiva\Desktop\ss_flask.jpg",image)
return "successfull"
app.run()
Till now, api/flask is running only if the image is present in my system ,if image is provided from other system it is not working, how to make api to run when image is loaded through any system?
N: The same api is hosted in the server, but requires image to be present in server and it is throwing error when image is not there in server.
So how to make this api working when image is given from any system?Please help, thanks :)
You can post the image: requests_post_files
client:
import requests
requests.post(url, files={'image': open('image.jpg', 'rb')})
server:
from flast import request
binary_image = request.files['image'].read()
with open('image.jpg', 'wb') as fid:
fid.write(binary_image)
Related
I am running my Flask app on Ubuntu VPS (linode) as server. I am capturing image from android studio sending it to flask server to get response. Image is being sent as base64 string from android studio.
But the response is too slow when using request.form.to_dict(). Both ubuntu vps and android app are running on different IP.
I've put timestamps on different processes and found this request.form.to_dict() is the problem taking around 22 to 35 secs.
I am also using image compressing techniques on my android studio code but still too much time.
Tried on gunicorn with nginx but same.
threaded = True
Images are of around 400kb to 500kb size.
Kindly help me to figure out this issue.
Below is my flask code:
#app.route('/predict', methods=['POST', 'GET'])
def predict():
if request.method == 'POST':
file = request.form.to_dict()['upload'] # 22.2491 sec
b64_string = file
image = imread(io.BytesIO(base64.b64decode(b64_string))) #0.0023 sec
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) # 0.000171 sec
.....
.....
.....
sending the images in base64 format is not the recommended method, you should try to send the photo via a multipart request.
Look here to see how to send an image from android in multipart form data (if you are using java).
If you send the images via multipart form data you will then be able to access them on flask using the method request.files['my_file_name']:
#app.route('/upload', methods=['POST'])
def upload_file():
my_file = request.files['my_file_name']:
I have a Django app working as the backend of an Android app. The thing is that the Android app sends an image to the Django server. Then the server makes some calculations and I need to return as the response the image modified and a float value that is calculated in the server.
It's pretty clear how to return only the image using HttpResponse:
def backend_function(request):
img = request.FILES["file"].read()
img_res, float_res = some_calculations(img)
return HttpResponse(img_res, content_type="image/jpeg")
But I don't know how to add that float_res to the HttpResponse.
You could append the float_res to the returned filename, or in the response header, or session.
I am trying to make an API that when a POST request is made, it will accept images and then save them, and if a GET request is made then it will send back a URL to where you'd be able to download that image. How would that be possible?
This is the Flask app running on localhost for testing:
from flask import Flask, send_file
app = Flask(__name__)
#app.route("/upload_image/<filename>", methods=["POST"])
def upload_image(filename):
# receive the image here
# ...
#app.route("/get_image", methods=["GET"])
def get_image():
filename = "encoded_image.png"
return send_file(filename, mimetype="image/png")
if __name__ == "__main__":
app.run(host="localhost", port=5000)
I think sending the image is easy but I don't know how to go about receiving it and using requests to send it.
This is the idea behind the main code:
import requests
option = input()
if option == "get image":
print("Download the image at: https://localhost:5000/get_image")
elif option == "upload image":
post = requests.post("https://localhost:5000/upload_image/encoded_image.png")
i don't want the images to change names. I always want to send the file encoded_image.png and receive it, because I want it to be overwritten when the POST is made. This is for a discord bot but that doesn't really affect anything, I just thought I'd mention it. Thanks in advance :)
I am building a "guitar tuner" app with ReactJS for frontend and Python Flask as the backend.
This is what the app does so far:
1. The React app (client side) records audio using react library react-mic
2. Sends the recording via. a fetch POST request to to Flask API, which picks it up and send as response back.
PROBLEM: The file being sent is on the form in the screenshot, which is a list with one Blob element consisting of a webm audio file.
When I send this blob file of a webM audio file in the fetch function it comes out as undefined in the Flask app, and I am unsure about how to read the blob/webm audio in Python.
The POST function in ReactJS:
uploadFile(file) {
var form = new FormData();
form.append('file',file)
form.append('title',"Guitar recording")
fetch('http://127.0.0.1:5000/audio_record', {
// content-type header should not be specified!
method: 'POST',
body: form
}).then(function (response){
return (response.text())
}).then(function(text){
console.log(text) // The text the endpoint returns
})
.catch(error => console.log(error)
);
}
Python flask app (where I try reading the file, does not work..):
import audioread
from flask import Flask, request #import main Flask class and request object
from flask_cors import CORS
import logging
from pydub import AudioSegment
from pydub.playback import play
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('HELLO WORLD')
app = Flask(__name__) #create the Flask app
CORS(app)
#app.route('/')
def landing():
return 'Landing page'
# Get the blob of type "audio/webm;codecs=opus"
#app.route('/audio_record', methods=['POST'])
def save_record():
logger.info("welcome to upload`")
# file = request.files['file']
#filename = secure_filename(file.title)
file = request.form['file']
print('File from the POST request is: {}'.format(file))
try:
read_audio_file(file[0])
return "****** Audio Read ******"
except:
print("In the except", file[0]) # Gets printed as undefined
title = request.form['title']
print(title) # Able to print title
return "Request received and responded"
# app.logger.debug(request.files['file'].filename)
def read_audio_file(audio_from_post):
print("Tring to read audio..")
with audioread.audio_open(audio_from_post) as f:
print(f.channels, f.samplerate, f.duration)
for buf in f:
print(buf)
if __name__ == '__main__':
app.run(debug=True, port=5000) #run app in debug mode on port 5000
I saw here that it might be smart to convert the Blob to an Audio object in ReactJS, but I am not sure how that would make the reading of the file in Flask any easier.
Any idea as to how I should do this?
I want to read the file in Python and do a Fast Fourier Transform (numpy.fft.fft), to determine the frequencies in the audio clip.
Thanks in advance!
UPDATE
I decided that I wanted to try recording the audio with another library, MediaRecorder- to be able to record audio in WAV, not webm. I think I will encode the WAV file in base64, send it in a form to Flask and read it with the wave library.
One way you could approach is by sending the data from the frontend is sending the blob of the recording instead of the whole object by making the following change to your POST function in React
form.append('file',file.blob)
Then, on the server-side, you could simply do the following
request.files['file'].filename
And then proceeding to save it by using the built-in save method for further processing. Documentation for request.files can be found here
I am using docker for a data-science project. The docker image contains a python code that reads a file(image file), processes it, and generates a vector of floats as an output.
I am using flask micro-framework for a user to interact with the container. Here is the server-side code (running inside the container). It is of course buggy!
from flask import Flask, request
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
#app.route('/process_image', methods=['GET', 'POST'])
def process_image():
params = request.json
with open(params["file_name"]. "r") as f:
# the above access to a file in host machine from docker container,
# will definetly lead to an access error.
# do some processing
pass
Here is the client-side code
import requests
file_name = "some-path/image.jpg" # on the host machine
requests.get('http://0.0.0.0:5000/process_image/', json={"file_name": file_name})
What is the right way to pass a file via requests to the container? I am looking at a solution where the client-side code is minimal and the user must be able to send a file stored at any location in the host-machine.
I am new to docker as well as web-programming, I would appreciate any feedback/suggestion. Thanks in advance!