-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
114 lines (97 loc) · 3.04 KB
/
app.py
File metadata and controls
114 lines (97 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
from flask import Flask, render_template, request, redirect, url_for, Response, make_response, send_file
import json, time, cv2, io, threading
from PIL import Image
from collections import Counter
import paho.mqtt.client as mqtt
app = Flask(__name__)
# Initialize the webcam
cap = cv2.VideoCapture(0)
# Voting options
options = ["Mia", "May"]
# Store user answers (in memory)
answers = []
# Path to JSON file used for shared data
spoke_path = "spoke.json"
def load_json(name):
"""
Load JSON data from a file.
Args:
name (str): File path.
Returns:
dict: Parsed JSON data.
"""
with open(name) as f:
return json.load(f)
def save_json(name, data):
"""
Save JSON data to a file.
Args:
name (str): File path.
data (dict): Data to save.
"""
with open(name, 'w') as f:
json.dump(data, f, indent=4)
def get_vote_cookie_key():
"""
Generate a unique cookie key to track if the user has voted.
Returns:
str: Unique cookie key.
"""
return "has_voted_" + "_".join(option.lower() for option in options)
def generate_frames():
"""
Generator function that captures frames from the camera and yields them as JPEG byte streams
for real-time video streaming over HTTP.
"""
prev = 0
while True:
time_elapsed = time.time() - prev
if time_elapsed > 1 / 15: # Limit to ~15 FPS
prev = time.time()
success, frame = cap.read()
if not success:
break
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/', methods=['GET', 'POST'])
def index():
"""
Render the main page and handle conversation and
places from the NLP.
"""
spoke = load_json(spoke_path)
return render_template('index.html', spoke=spoke)
@app.route('/video')
def video():
"""
Stream live video from the camera to the browser using multipart/x-mixed-replace.
"""
return Response(generate_frames(),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/frame.jpg')
def frame():
"""
Capture a single frame from the camera and return it as a JPEG image.
"""
try:
temp_cap = cv2.VideoCapture(0)
if not temp_cap.isOpened():
return "Camera error", 500
success, frame = temp_cap.read()
temp_cap.release()
if not success:
return "Frame capture failed", 500
# Convert OpenCV image (BGR) to PIL Image (RGB)
img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
buf = io.BytesIO()
img.save(buf, format='JPEG')
buf.seek(0)
return send_file(buf, mimetype='image/jpeg')
except Exception as e:
print(f"Frame capture exception: {e}")
return "Internal error", 500
if __name__ == '__main__':
# Start the Flask app
app.run(host='0.0.0.0', port=5000, threaded=True)