zolodickk commited on
Commit
e93d662
·
verified ·
1 Parent(s): 721cf91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -17
app.py CHANGED
@@ -1,32 +1,84 @@
1
- from flask import Flask, Response, render_template
 
 
2
  import cv2
3
- import base64
 
 
 
 
4
 
5
- app = Flask(__name__)
6
- camera = cv2.VideoCapture(0)
7
 
 
 
 
 
8
  def generate_frames():
 
9
  while True:
 
10
  success, frame = camera.read()
11
  if not success:
12
  break
13
  else:
14
- # Preprocess the frame here (e.g., resize, color conversion)
15
- processed_frame = frame # Placeholder for preprocessing
16
-
17
- _, buffer = cv2.imencode('.jpg', processed_frame)
18
- frame_bytes = base64.b64encode(buffer.tobytes()).decode('utf-8')
19
-
20
- yield frame_bytes
21
 
 
22
  @app.route('/')
23
  def index():
24
  return render_template('index.html')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- @app.route('/capture_frame', methods=['GET', 'POST'])
27
- def capture_frame():
28
- frame = next(generate_frames())
29
- return frame
30
 
31
- if __name__ == '__main__':
32
- app.run(debug=True)
 
 
1
+ # Import necessary modules
2
+ from flask import Flask, render_template, Response, request, jsonify, redirect, url_for
3
+ from aiortc import RTCPeerConnection, RTCSessionDescription
4
  import cv2
5
+ import json
6
+ import uuid
7
+ import asyncio
8
+ import logging
9
+ import time
10
 
11
+ # Create a Flask app instance
12
+ app = Flask(__name__, static_url_path='/static')
13
 
14
+ # Set to keep track of RTCPeerConnection instances
15
+ pcs = set()
16
+
17
+ # Function to generate video frames from the camera
18
  def generate_frames():
19
+ camera = cv2.VideoCapture(0)
20
  while True:
21
+ start_time = time.time()
22
  success, frame = camera.read()
23
  if not success:
24
  break
25
  else:
26
+ ret, buffer = cv2.imencode('.jpg', frame)
27
+ frame = buffer.tobytes()
28
+ # Concatenate frame and yield for streaming
29
+ yield (b'--frame\r\n'
30
+ b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
31
+ elapsed_time = time.time() - start_time
32
+ logging.debug(f"Frame generation time: {elapsed_time} seconds")
33
 
34
+ # Route to render the HTML template
35
  @app.route('/')
36
  def index():
37
  return render_template('index.html')
38
+ # return redirect(url_for('video_feed')) #to render live stream directly
39
+
40
+ # Asynchronous function to handle offer exchange
41
+ async def offer_async():
42
+ params = await request.json
43
+ offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
44
+
45
+ # Create an RTCPeerConnection instance
46
+ pc = RTCPeerConnection()
47
+
48
+ # Generate a unique ID for the RTCPeerConnection
49
+ pc_id = "PeerConnection(%s)" % uuid.uuid4()
50
+ pc_id = pc_id[:8]
51
+
52
+ # Create a data channel named "chat"
53
+ # pc.createDataChannel("chat")
54
+
55
+ # Create and set the local description
56
+ await pc.createOffer(offer)
57
+ await pc.setLocalDescription(offer)
58
+
59
+ # Prepare the response data with local SDP and type
60
+ response_data = {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}
61
+
62
+ return jsonify(response_data)
63
+
64
+ # Wrapper function for running the asynchronous offer function
65
+ def offer():
66
+ loop = asyncio.new_event_loop()
67
+ asyncio.set_event_loop(loop)
68
+
69
+ future = asyncio.run_coroutine_threadsafe(offer_async(), loop)
70
+ return future.result()
71
+
72
+ # Route to handle the offer request
73
+ @app.route('/offer', methods=['POST'])
74
+ def offer_route():
75
+ return offer()
76
 
77
+ # Route to stream video frames
78
+ @app.route('/video_feed')
79
+ def video_feed():
80
+ return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
81
 
82
+ # Run the Flask app
83
+ if __name__ == "__main__":
84
+ app.run(debug=True, host='0.0.0.0')