File size: 4,259 Bytes
1a6d541 6c5ef18 1a6d541 6c5ef18 1a6d541 | 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | from fastapi import FastAPI, Response, WebSocket
from fastapi.exceptions import WebSocketRequestValidationError
import openai
import os
from starlette.websockets import WebSocket, WebSocketDisconnect
from io import BytesIO
import torch
import torchaudio
import audioop
import base64
import json
from flask import Flask, request
from flask_sock import Sock, ConnectionClosed
from twilio.twiml.voice_response import VoiceResponse, Start
from twilio.rest import Client
import vosk
messages = [ {"role": "system", "content":
"You are a intelligent assistant."} ]
SAMPLE_RATE = 16_000
openai.api_key = os.environ.get("OPEN_API_KEY")
# Create a new FastAPI app instance
app = FastAPI()
twilio_client = Client()
model = vosk.Model('/tmp/model/vosk-model-small-fr-0.22')
CL = '\x1b[0K'
BS = '\x08'
"""
public_url = "https://jibay-test.hf.space/call"
number = twilio_client.incoming_phone_numbers.list()[0]
number.update(voice_url=public_url)
print("ok serveur")
print(__name__)
"""
# Define a function to handle the GET request at `/generate`
# The generate() function is defined as a FastAPI route that takes a
# string parameter called text. The function generates text based on the # input using the pipeline() object, and returns a JSON response
# containing the generated text under the key "output"
@app.get("/generate")
def generate(text: str):
messages.append(
{"role": "user", "content":
"peux-tu me dire s'il faut appeler les secours, quelqu'un m'a ecrit ceci: \"ah mon dieu je suis tombé vite sauvez-moi viii vous pouvez intervenir ah ça va pas du tout là s'il vous plaît s'il vous plaît\" ?"},
)
chat = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=messages
)
reply = chat.choices[0].message.content
# Return the generated text in a JSON response
return {"output": reply}
@app.get("/")
def read_root():
return {"Hello": "World!"}
@app.post('/call')
def call():
print("ok3")
"""Accept a phone call."""
response = VoiceResponse()
start = Start()
start.stream(url=f'wss://jibay-test.hf.space/audio-stream')
print("ok2")
response.append(start)
response.say('Please leave a message from the city')
response.pause(length=60)
print("ok")
print(response)
#print(f'Incoming call from {request.form["From"]}')
return Response(content=response.to_xml(), media_type="application/xml")
@app.websocket("/audio-stream")
async def stream(ws: WebSocket):
"""Receive and transcribe audio stream."""
try:
print("problem 2")
await ws.accept()
except WebSocketRequestValidationError as e:
print("problem 1")
await ws.close(code=1000)
raise e
"""Receive and transcribe audio stream."""
rec = vosk.KaldiRecognizer(model, 16000)
while True:
message = await ws.receive()
print("here")
print(message.text)
print(json.loads(message.text))
#packet = json.loads(message)
packet = message
if packet['event'] == 'start':
print('Streaming is starting')
elif packet['event'] == 'stop':
print('\nStreaming has stopped')
elif packet['event'] == 'media':
audio = base64.b64decode(packet['media']['payload'])
audio = audioop.ulaw2lin(audio, 2)
audio = audioop.ratecv(audio, 2, 1, 8000, 16000, None)[0]
if rec.AcceptWaveform(audio):
r = json.loads(rec.Result())
#print(CL + r['text'] + ' ', end='', flush=True)
print(r['text'] + ' ', end='', flush=True)
else:
r = json.loads(rec.PartialResult())
#print(CL + r['partial'] + BS * len(r['partial']), end='', flush=True)
#print(CL + r['partial'] + BS * len(r['partial']), end='', flush=True)
if __name__ == 'app':
#from pyngrok import ngrok
print("tessst")
port = 5000
public_url = "https://jibay-test.hf.space/call"
print(twilio_client.incoming_phone_numbers.list())
number = twilio_client.incoming_phone_numbers.list()[1]
number.update(voice_url=public_url)
print(f'Waiting for calls on {number.phone_number}') |