rohaneng/transcript_api
0
1from fastapi import FastAPI, WebSocket, WebSocketDisconnect2import random3import asyncio4 5app = FastAPI()6 7# Predefined list of sentences to simulate a transcript8SENTENCES = [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 19def 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 sentence27 28# Store the previous sentence for the normal API29previous_sentence = None30 31@app.get("/normal-transcript")32def normal_transcript():33 """34 Normal API endpoint that returns a new sentence each time it is called.35 """36 global previous_sentence37 sentence = get_random_sentence(previous_sentence)38 previous_sentence = sentence39 return {"transcript": sentence}40 41@app.websocket("/ws/realtime-transcript")42async 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 = None49 try:50 while True:51 # Generate a random sentence52 current_sentence = get_random_sentence(previous_sentence)53 # Send the sentence to the client54 await websocket.send_text(current_sentence)55 # Update the previous sentence to avoid repetition56 previous_sentence = current_sentence57 # Simulate delay for real-time streaming58 await asyncio.sleep(0.5) # 0.5 second delay59 except WebSocketDisconnect:60 print("Client disconnected")