Skip to content

Commit

Permalink
Merge pull request #4 from software-students-spring2024/alex
Browse files Browse the repository at this point in the history
camera fix
  • Loading branch information
jp6024 authored Apr 27, 2024
2 parents 76283d6 + 67b7ef8 commit 3cda858
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 51 deletions.
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ services:
- mongodb
ports:
- "5002:5000"
devices:
- "/dev/video0:/dev/video0"
networks:
- app-network

Expand Down
81 changes: 31 additions & 50 deletions web-app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,62 +56,51 @@
@app.route("/processing/<image_id>")
def processing(image_id):
"""
Instead of threading, let's call process_image directly.
Instead of threading, calling the process_image directly.
"""
try:
grid_out = fs.get(bson.ObjectId(image_id))
_, temp_filepath = tempfile.mkstemp()
with open(temp_filepath, "wb") as f:
f.write(grid_out.read())
with open(temp_filepath, "rb") as file:
requests.post(
"http://machine-learning-client:5001/analyze",
files={"file": file},
data={"image_id": str(image_id)},
timeout=1000,
)

requests.post("http://machine-learning-client:5001/analyze", files={"file": file}, data={"image_id": str(image_id)}, timeout=1000)
wait_interval = 5

while True:
current_image_doc = images_collection.find_one(
{"image_id": bson.ObjectId(image_id)}
)
current_image_doc = images_collection.find_one({"image_id": bson.ObjectId(image_id)})
if current_image_doc and current_image_doc.get("status") == "success":
return redirect(url_for("show_results", image_id=image_id))
if current_image_doc and current_image_doc.get("status") == "failed":
# call a method that prints an error message to the screen/ add exception
app.logger.error("error occurred.")

flash("Processing failed", "error")
app.logger.error("Processing failed for image ID %s", image_id)
time.sleep(wait_interval)
# call a method that prints an error message to the screen
except bson.errors.InvalidId:
flash("Invalid image ID provided.", "error")
app.logger.error("Invalid image_id provided.")
return jsonify({"error": "Invalid image ID"}), 400

# capturing the photo
@app.route('/capture_photo', methods=['GET'])
def capture_photo():
"""
Function to capture a user photo
"""
camera = cv2.VideoCapture(0) # initialize camera

try:
# capture camera frame
success, frame = camera.read()
success, frame = camera.read()
if success:
# specify directory path
save_directory = './shots/'
filename = f'captured_photo_{int(time.time())}.jpg'

# save
cv2.imwrite(os.path.join(save_directory, filename), frame)

# stop camera
if not os.path.exists(save_directory):
os.makedirs(save_directory)
filename = f'captured_photo_{int(time.time())}.jpg'
filepath = os.path.join(save_directory, filename)
cv2.imwrite(filepath, frame)
camera.release()

return jsonify({'message': 'Photo captured and saved successfully', 'filename': filename}), 200
else:
return jsonify({'error': 'Failed to capture photo'}), 500
except Exception as e:
camera.release() # Ensure camera is released on error
return jsonify({'error': f'Error capturing photo: {str(e)}'}), 500

def allowed_file(filename):
Expand Down Expand Up @@ -184,40 +173,32 @@ def upload_image():
or re-render the upload page with appropriate error messages if not.
"""
if request.method == "POST":
if "image" not in request.files or "age" not in request.form:
image = request.files.get("image")
actual_age = request.form.get("age")
if not image or not actual_age:
flash("Missing data", "error")
return jsonify({"error": "Missing data"}), 400
image = request.files["image"]
actual_age = request.form["age"]
if image.filename == "":
flash("No selected file", "error")
return jsonify({"error": "No selected file"}), 400
if image and allowed_file(image.filename):
filename = secure_filename(image.filename)
try:
image_id = fs.put(image, filename=filename)
images_collection.insert_one(
{
"image_id": image_id,
"filename": filename,
"status": "pending",
"upload_date": datetime.now(),
"actual_age": str(actual_age),
}
)
return (
jsonify(
{
"message": "File uploaded successfully",
"task_id": str(image_id),
}
),
200,
)
except FileNotFoundError as e:
images_collection.insert_one({
"image_id": image_id,
"filename": filename,
"status": "pending",
"upload_date": datetime.now(),
"actual_age": actual_age,
})
return jsonify({"message": "File uploaded successfully", "task_id": str(image_id)}), 200
except Exception as e:
flash("File upload failed", "error")
app.logger.error("File upload failed: %s", str(e))
return jsonify({"error": "File not found"}), 500
return jsonify({"error": "File upload failed"}), 500
else:
flash("Invalid file type", "error")
return jsonify({"error": "Invalid file type"}), 400
return render_template("upload.html")

Expand Down
20 changes: 19 additions & 1 deletion web-app/templates/upload.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,31 @@
}
})
.then(data => {
// Update the form to include the captured photo path for submission
const imgForm = document.getElementById('uploadForm');
const imgInput = document.getElementById('image');
imgInput.style.display = 'none'; // Hide the file input
const newImage = document.createElement("input");
newImage.setAttribute("type", "hidden");
newImage.setAttribute("name", "captured_photo");
newImage.setAttribute("value", data.filename);
imgForm.appendChild(newImage);

const imageDisplay = document.createElement("img");
imageDisplay.src = `/shots/${data.filename}`; // Adjust according to actual path
imageDisplay.alt = 'Captured Photo';
imageDisplay.style.maxWidth = '300px';
imageDisplay.style.maxHeight = '300px';
document.querySelector('.container').appendChild(imageDisplay);

alert(`Photo captured and saved successfully: ${data.filename}`);
})
.catch(error => {
console.error('Error capturing photo:', error);
alert('Error capturing photo');
alert('Error capturing photo: ' + error.message);
});
}

</script>
</head>
<body>
Expand Down

0 comments on commit 3cda858

Please sign in to comment.