rohaneng commited on
Commit
0bca7b9
·
verified ·
1 Parent(s): ca3ec61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py CHANGED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
2
+ import random
3
+ import asyncio
4
+
5
+ app = FastAPI()
6
+
7
+ # Predefined list of sentences to simulate a transcript
8
+ SENTENCES = [
9
+ "Hello, how are you doing today?",
10
+ "This is a simulated transcript.",
11
+ "FastAPI makes building APIs fun and fast.",
12
+ "Let's create a mock real-time transcript generator.",
13
+ "This sentence is unique in the stream.",
14
+ "Here's another unique sentence for variety.",
15
+ "Real-time transcripts can be exciting to work with!",
16
+ "The API ensures no consecutive repeats of sentences.",
17
+ ]
18
+
19
+ def get_random_sentence(previous_sentence: str = None) -> str:
20
+ """
21
+ Returns a random sentence from the list, ensuring no consecutive repeats.
22
+ """
23
+ while True:
24
+ sentence = random.choice(SENTENCES)
25
+ if sentence != previous_sentence:
26
+ return sentence
27
+
28
+ # Store the previous sentence for the normal API
29
+ previous_sentence = None
30
+
31
+ @app.get("/normal-transcript")
32
+ def normal_transcript():
33
+ """
34
+ Normal API endpoint that returns a new sentence each time it is called.
35
+ """
36
+ global previous_sentence
37
+ sentence = get_random_sentence(previous_sentence)
38
+ previous_sentence = sentence
39
+ return {"transcript": sentence}
40
+
41
+ @app.websocket("/ws/realtime-transcript")
42
+ async def websocket_endpoint(websocket: WebSocket):
43
+ """
44
+ WebSocket endpoint for real-time transcript streaming.
45
+ Sends sentences one at a time with a delay.
46
+ """
47
+ await websocket.accept()
48
+ previous_sentence = None
49
+ try:
50
+ while True:
51
+ # Generate a random sentence
52
+ current_sentence = get_random_sentence(previous_sentence)
53
+ # Send the sentence to the client
54
+ await websocket.send_text(current_sentence)
55
+ # Update the previous sentence to avoid repetition
56
+ previous_sentence = current_sentence
57
+ # Simulate delay for real-time streaming
58
+ await asyncio.sleep(1) # 1 second delay
59
+ except WebSocketDisconnect:
60
+ print("Client disconnected")