Spaces:
Build error

test / app2.py
jibay
Modif
6c5ef18
Raw History Blame Contribute Delete
4.26 kB
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}')