Sip phone in python using pyVoIP

hey here is my code i want to call from this code to asterisk
import logging
import pyVoIP # Note the capitalization
from pyVoIP.VoIP import VoIPPhone, CallState
import speech_recognition as sr
import uuid
import pywav
from pydub import AudioSegment
import os
import shutil
import time

Set up logging

logging.basicConfig(
level=logging.DEBUG, # Log all levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
format=‘%(asctime)s - %(levelname)s - %(message)s’, # Log format
handlers=[
logging.FileHandler(“voip_log.log”), # Save logs to a file
logging.StreamHandler() # Also output logs to the console
]
)
pyVoIP.DEBUG = True

Check if FFmpeg is installed

ffmpeg_path = shutil.which(“ffmpeg”)
if ffmpeg_path:
logging.info(f"FFmpeg found at: {ffmpeg_path}")
else:
logging.error(“FFmpeg not found in PATH”)

Create a simple test audio file if it doesn’t exist

try:
if not os.path.exists(“test.wav”):
from pydub.generators import Sine
sound = Sine(440).to_audio_segment(duration=5000) # 1-second tone
sound.export(“test.wav”, format=“wav”)
logging.info(“Test audio file ‘test.wav’ created.”)
test_audio = AudioSegment.from_file(“test.wav”)
logging.info(“FFmpeg is correctly configured.”)
except Exception as e:
logging.error(f"Error with FFmpeg configuration: {e}")

Convert audio to WAV format

def convert_to_wav(audio, tmpFileName):
try:
data_bytes = b"“.join(audio)
wave_write = pywav.WavWrite(tmpFileName, 1, 8000, 8, 7)
wave_write.write(data_bytes)
wave_write.close()
logging.info(f"Audio converted to WAV and saved as {tmpFileName}”)
return tmpFileName
except Exception as e:
logging.error(f"Error converting audio to WAV: {e}")
return None

Transcribe audio to text using Sphinx

def transcribe_to_text(audio_file):
recognizer = sr.Recognizer()
try:
with sr.AudioFile(audio_file) as source:
audio = recognizer.record(source)
transcription = recognizer.recognize_sphinx(audio)
logging.info(f"Transcription successful: {transcription}“)
return transcription
except sr.UnknownValueError:
logging.warning(“Sphinx could not understand the audio.”)
except sr.RequestError as e:
logging.error(f"Sphinx error; {e}”)
return “”

Function to answer a call

def answer(call):
try:
call.answer()
logging.info(“Call answered.”)
# Log call details for debugging
logging.info(f"Call details: {call}")
buffer =
buff_length = 0

    # Process audio while the call is in the ANSWERED state
    while call.state == CallState.ANSWERED:
        audio = call.read_audio()
        buff_length += len(audio) / 8  # Sample rate is 8000 Hz

        if buff_length <= 1000:  # Buffer until 1000ms
            buffer.append(audio)
        else:
            # Save audio to a temporary .wav file for transcription
            tmpFileName = f"./_audio_buffer_{uuid.uuid4()}.wav"
            if convert_to_wav(buffer, tmpFileName):
                transcription = transcribe_to_text(tmpFileName)
                logging.info(f"Transcription: {transcription}")
            buffer = []
            buff_length = 0
except Exception as e:
    logging.error(f"Error during call processing: {e}")
finally:
    call.hangup()
    logging.info("Call hung up.")

Function to register the phone and handle retries

def register_phone():
contact_address = f"sip:[email protected]:5060"
vp = VoIPPhone(‘asterisk ip’, 5060, ‘phone’, ‘passowrd’, callCallback=answer)
vp.start()

# Add detailed logging during registration
max_retries = 5
retry_count = 0
while vp._status == 'REGISTERING' and retry_count < max_retries:
    time.sleep(5)
    logging.info(f"Phone is still registering... Attempt {retry_count + 1}")
    retry_count += 1

if vp._status == 'REGISTERED':
    logging.info(f"Phone successfully registered with status: {vp._status}")
else:
    logging.error(f"Phone failed to register after {max_retries} attempts. Current status: {vp._status}")
    # Log SIP response if available for debugging
    logging.debug(f"SIP response: {vp.sip_response if hasattr(vp, 'sip_response') else 'No response available'}")

return vp

Start the phone registration process

vp = register_phone()

Wait for registration to complete

if vp._status == ‘REGISTERED’:
logging.info(“Phone is ready to make and receive calls.”)
else:
logging.error(“Phone registration failed. Exiting.”)

Keep the script running to handle calls

try:
input(“Press any key to exit the VOIP phone session.”)
finally:
vp.stop()
logging.info(“VOIP phone session stopped.”)
when i run at show me an error 2024-09-12 15:14:07,591 - ERROR - Phone failed to register. Current status: Phon eStatus.REGISTERED
Press any key to exit the VOIP phone session.TODO: Add 500 Error on Receiving SI P Response
and some time this Error on header parsing: Unable to decipher SIP request: NOTIFY sip:[email protected]:5060;transport=UDP SIP/2.0
Error on header parsing: Unable to decipher SIP request: OPTIONS sip:[email protected]:5060;transport=UDP SIP/2.0
Error on header parsing: Unable to decipher SIP request: NOTIFY sip:[email protected]:5060;transport=UDP SIP/2.0
Error on header parsing: Unable to decipher SIP request: OPTIONS sip:[email protected]:5060;transport=UDP SIP/2.0
Error on header parsing: Unable to decipher SIP request: OPTIONS sip:[email protected]:5060;transport=UDP SIP/2.0