Skip to content

Commit

Permalink
Added blob storage to stoge & depth map.
Browse files Browse the repository at this point in the history
  • Loading branch information
akashmishra242 committed Oct 1, 2023
1 parent 4975468 commit c73dce7
Show file tree
Hide file tree
Showing 6 changed files with 258 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
Binary file added __pycache__/azure_blob_functions.cpython-310.pyc
Binary file not shown.
89 changes: 87 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import cv2
import numpy as np
from flask import Flask, request, make_response
from flask import Flask, request, make_response, jsonify
import requests
from io import BytesIO
import os
from azure_blob_functions import upload_file_and_get_link, download_from_blob_storage

app = Flask(__name__)

Expand Down Expand Up @@ -35,5 +39,86 @@ def create_depth_map():
response.headers.set('Content-Disposition', 'attachment', filename='depth_map.png')
return response

@app.route('/azure-blob-depth-map', methods=['POST'])
def create_azure_blob_depth_map():
# Retrieve the image URLs from the request
left_image_url = request.form.get('left_image_url')
right_image_url = request.form.get('right_image_url')

# Prompt the user to input values for numDisparities and blockSize
numDisparities = int(request.form.get('numDisparities', 16))
blockSize = int(request.form.get('blockSize', 15))

# Download the images from the URLs
left_image_response = requests.get(left_image_url)
right_image_response = requests.get(right_image_url)

if left_image_response.status_code != 200 or right_image_response.status_code != 200:
return "Failed to fetch images from the provided URLs", 400

# Read the images and convert them to grayscale
img1 = cv2.imdecode(np.frombuffer(left_image_response.content, np.uint8), cv2.IMREAD_GRAYSCALE)
img2 = cv2.imdecode(np.frombuffer(right_image_response.content, np.uint8), cv2.IMREAD_GRAYSCALE)

# Compute the depth map using OpenCV's StereoBM
stereo = cv2.StereoBM_create(numDisparities=numDisparities, blockSize=blockSize)
depth = stereo.compute(img1, img2)

# Convert the depth map to a PNG image
depth_png = cv2.imencode('.png', depth)[1]

# Return the depth map as a response
response = make_response(depth_png.tobytes())
response.headers.set('Content-Type', 'image/png')
response.headers.set('Content-Disposition', 'attachment', filename='depth_map.png')
return response


# Flask route to compute and upload a depth map
@app.route('/compute-and-upload-fetch-depth-map', methods=['POST'])
def compute_and_upload_depth_map_route():
# Retrieve the image URLs from the request
left_image_url = request.form.get('left_image_url')
right_image_url = request.form.get('right_image_url')

# Prompt the user to input values for numDisparities and blockSize
numDisparities = int(request.form.get('numDisparities', 16))
blockSize = int(request.form.get('blockSize', 15))

#get container name and the file name which be want to keep
container_name = request.form.get('container_name')
file_name = request.form.get('file_name')
firstname_name, extension = os.path.splitext(file_name)
if not extension:
file_name += ".png"

# Download the images from the URLs
left_image_response = requests.get(left_image_url)
right_image_response = requests.get(right_image_url)

if left_image_response.status_code != 200 or right_image_response.status_code != 200:
return "Failed to fetch images from the provided URLs", 400

# Read the images and convert them to grayscale
img1 = cv2.imdecode(np.frombuffer(left_image_response.content, np.uint8), cv2.IMREAD_GRAYSCALE)
img2 = cv2.imdecode(np.frombuffer(right_image_response.content, np.uint8), cv2.IMREAD_GRAYSCALE)

# Compute the depth map using OpenCV's StereoBM
stereo = cv2.StereoBM_create(numDisparities=numDisparities, blockSize=blockSize)
depth = stereo.compute(img1, img2)

# Convert the depth map to a PNG image
depth_png = cv2.imencode('.png', depth)[1]

#upload depth_map_and get link
try:
blob_url= upload_file_and_get_link(depth_png.tobytes(), file_name=file_name, container_name=container_name)

#response
return jsonify({"message": "Depth-Map Created Uploaded and Link Created Successfully", "blob_url": blob_url}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
app.run(debug=True)
app.run(debug=True)
62 changes: 62 additions & 0 deletions azure_blob_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Import the necessary modules
from flask import Flask, request, jsonify, send_file, make_response
from azure.storage.blob import BlobServiceClient
import os
from dotenv import load_dotenv
import mimetypes # Import the mimetypes module

load_dotenv() # Load environment variables from .env
AZURE_STORAGE_ACCOUNT_NAME = os.getenv("AZURE_STORAGE_ACCOUNT_NAME")
AZURE_STORAGE_ACCOUNT_KEY = os.getenv("AZURE_STORAGE_ACCOUNT_KEY")

# Function to create a BlobServiceClient using your credentials
def create_blob_service_client():
connection_string = f"DefaultEndpointsProtocol=https;AccountName={AZURE_STORAGE_ACCOUNT_NAME};AccountKey={AZURE_STORAGE_ACCOUNT_KEY};EndpointSuffix=core.windows.net"
return BlobServiceClient.from_connection_string(connection_string)

# Function to upload a file to Azure Blob Storage and get the link
def upload_file_and_get_link(file_data, file_name, container_name):
try:
blob_service_client = create_blob_service_client()
container_client = blob_service_client.get_container_client(container_name)

# Create the container if it doesn't exist
if not container_client.exists():
container_client.create_container()

# Upload the file
blob_client = container_client.get_blob_client(file_name)
blob_client.upload_blob(file_data)

# Get the public URL of the uploaded file
blob_url = blob_client.url

return blob_url
except Exception as e:
raise RuntimeError(f"Error uploading file: {str(e)}")

# Function to download a file from Azure Blob Storage
def download_from_blob_storage(container_name, file_name):
try:
blob_service_client = create_blob_service_client()
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(file_name)

if blob_client.exists():
blob_data = blob_client.download_blob()
content_type, _ = mimetypes.guess_type(file_name) # Determine content type based on file extension

if content_type:
response = make_response(blob_data.readall())
response.headers["Content-Type"] = content_type
else:
# Default to application/octet-stream for unknown file types
response = make_response(blob_data.readall())
response.headers["Content-Type"] = "application/octet-stream"

response.headers["Content-Disposition"] = f'attachment; filename="{file_name}"'
return response
else:
return jsonify({"error": "File not found"}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500
105 changes: 105 additions & 0 deletions blob_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Import the necessary modules
from flask import Flask, request, jsonify, send_file, make_response
from azure.storage.blob import BlobServiceClient
import os
from dotenv import load_dotenv
import mimetypes # Import the mimetypes module

app = Flask(__name__)

load_dotenv() # Load environment variables from .env
AZURE_STORAGE_ACCOUNT_NAME = os.getenv("AZURE_STORAGE_ACCOUNT_NAME")
AZURE_STORAGE_ACCOUNT_KEY = os.getenv("AZURE_STORAGE_ACCOUNT_KEY")

# Function to create a BlobServiceClient using your credentials
def create_blob_service_client():
connection_string = f"DefaultEndpointsProtocol=https;AccountName={AZURE_STORAGE_ACCOUNT_NAME};AccountKey={AZURE_STORAGE_ACCOUNT_KEY};EndpointSuffix=core.windows.net"
return BlobServiceClient.from_connection_string(connection_string)

# Function to upload a file to Azure Blob Storage and get the link
def upload_file_and_get_link(file_data, file_name, container_name):
try:
blob_service_client = create_blob_service_client()
container_client = blob_service_client.get_container_client(container_name)

# Create the container if it doesn't exist
if not container_client.exists():
container_client.create_container()

# Upload the file
blob_client = container_client.get_blob_client(file_name)
blob_client.upload_blob(file_data)

# Get the public URL of the uploaded file
blob_url = blob_client.url

return blob_url
except Exception as e:
raise RuntimeError(f"Error uploading file: {str(e)}")

# Function to download a file from Azure Blob Storage
def download_from_blob_storage(container_name, file_name):
try:
blob_service_client = create_blob_service_client()
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(file_name)

if blob_client.exists():
blob_data = blob_client.download_blob()
content_type, _ = mimetypes.guess_type(file_name) # Determine content type based on file extension

if content_type:
response = make_response(blob_data.readall())
response.headers["Content-Type"] = content_type
else:
# Default to application/octet-stream for unknown file types
response = make_response(blob_data.readall())
response.headers["Content-Type"] = "application/octet-stream"

response.headers["Content-Disposition"] = f'attachment; filename="{file_name}"'
return response
else:
return jsonify({"error": "File not found"}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500

# Flask route to upload a file
@app.route('/upload', methods=['POST'])
def upload_file_and_get_link_route():
try:
# Get the file, container name, and file name from the request
uploaded_file = request.files['file']
if not uploaded_file:
return jsonify({"error": "No file provided"}), 400

container_name = request.form.get('container_name')
file_name = request.form.get('file_name')

if not container_name or not file_name:
return jsonify({"error": "Container name and file name must be provided"}), 400

# Upload the file to Azure Blob Storage and get the link
blob_url = upload_file_and_get_link(uploaded_file.read(), file_name, container_name)

return jsonify({"message": "File uploaded successfully", "blob_url": blob_url}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500


# Flask route to download a file
@app.route('/download', methods=['GET'])
def download_file_route():
try:
data = request.get_json()
container_name = data.get('container_name')
file_name = data.get('file_name')

if not container_name or not file_name:
return jsonify({"error": "Container name and file name must be provided"}), 400

return download_from_blob_storage(container_name, file_name)
except Exception as e:
return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
app.run(debug=True, port=5001)
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ Flask==2.2.2
numpy
matplotlib
opencv-python
gunicorn
gunicorn
azure-storage-blob
python-dotenv

0 comments on commit c73dce7

Please sign in to comment.