#!/usr/bin/env python3 #audio_recognizer.py

import speech_recognition as sr
import sys
import asyncio
from corcel import Corcel

#for index, name in enumerate(sr.Microphone.list_microphone_names()):
#print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name))
#sys.exit()

text_results = ""
voice_call_started = True
provider = Corcel()
queue = []

def detect_voice():
    global text_results, voice_call_started

    device_index = 6
    r = sr.Recognizer()

    with sr.Microphone(device_index=device_index) as source:
        print("Menyesuaikan untuk kebisingan lingkungan... Mohon tunggu.")
        r.adjust_for_ambient_noise(source)
        print("Siap. Silakan berbicara.")

        while True:
            if not queue:
                print("Say something!")
                audio = r.listen(source, phrase_time_limit=4)
                # audio = r.listen(source)
                # print("Audio")
                # print(audio)
                # print()

                try:
                    r_text_results = r.recognize_google(audio, language='id-ID')
                    text_results = provider.chat(f"{r_text_results}\njawab dengan singkat!", history=[])

                    print("R_TEXT_RESULTS")
                    print(r_text_results)
                    queue.append(1)
                except sr.UnknownValueError:
                    print("Could not understand audio")
                except sr.RequestError as e:
                    print("Could not request results {0}".format(e))

async def main():
    loop = asyncio.get_event_loop()
    task = loop.create_task(await asyncio.to_thread(detect_voice))

    await asyncio.gather(task)

if __name__ == "__main__":
    asyncio.run(main())


############## app.py(main)
import asyncio
import os
import sys
import threading
import audiorecognizer as ar

from gtts import gTTS

from pytgcalls import PyTgCalls
from pytgcalls import idle
from pytgcalls.types import (MediaStream, Update, GroupCallParticipant)
from pytgcalls import filters as call_filters
from pytgcalls.media_devices import MediaDevices

from pyrogram import Client
from pyrogram.raw import functions, base
# from pyrogram import

exit_event = threading.Event()

acc = {
    "s3rverdenied": {
        "name": "acc",
        "api_id": 26096884,
        "api_hash": "0a17b16cfe5e7f0297f4f0eca155b92d",
        "phone_number": "+6281818475959",
        "session_string": "BQGONPQANJQm-VG6XVT-GoK3DAeIyAbmC0q-t5CvHTuFo_AOFjF9zHoJ6M2cYdKkE0lFXLHLLXltyTCVwQA-KfMCgpjcGB8JVT2FoxCgIsoYUnOhXP9i2vNZFD8_DY4c4mZq2SPCr3ymI_nTf7Q-vvMe-lbNVSy6WWZtvoe8HhR8p5z9ZUXKZRH-bO3dSaj49FcAjKTlKBVKEUCBksG-cZp4H3dniUwf-bU1lHWV7dPgUAShr4If37A3IdCem0t0wNMlvvzDA_2N0sGFM_irAWM_4H8Lkv-_-5hY-gpUXObRwnJo695wEOZHqJbJgclhDBJ1-F4e9C2vkrQFSQlw9N50KF-7tgAAAAAiSSfLAA"
    }
}

client = Client(**acc["s3rverdenied"])
app = PyTgCalls(client)

def handle_exit(signum, frame):
    exit_event.set()
    print("Exit signal received.")

@app.on_update(call_filters.stream_end)
async def handler(client: PyTgCalls, update: Update):
    ar.queue.pop()
    ar.voice_call_started = True
    # remote="https://docs.evostream.com/sample_content/assets/popwed240p.mp4"
    # await app.play(
    #     "-1002076542041",
    #     MediaStream(
    #         remote
    #     )
    # )
    # await app.leave_call("-1001218880477")
    # pass
    # print(update)

async def start_proc(loop):
    loop.create_task(asyncio.to_thread(ar.detect_voice))
    ar.voice_call_started = True

    while True:
        if ar.queue and ar.voice_call_started:
            ar.voice_call_started = False
            print("Text Results")
            print(ar.text_results)
            tts = gTTS(ar.text_results, lang='id')
            ar.text_results = ""
            file_path = "./input.mp3"
            tts.save("./input.mp3")
            await app.play(
                "-1001218880477",
                MediaStream(
                    file_path
                )
            )

        await asyncio.sleep(1)


async def main():
    await app.start()
    loop = asyncio.get_event_loop()
    loop.create_task(start_proc(loop))
    await idle()

        # remote = 'http://docs.evostream.com/sample_content/assets/sintel1m720p.mp4'
        # await app.play(
        #     "-1002076542041",
        #     MediaStream(
        #         remote
        #     )
        # )


if __name__ == "__main__":
    import signal

    # Register the signal handler for graceful shutdown
    signal.signal(signal.SIGINT, handle_exit)

    try:
        asyncio.get_event_loop().run_until_complete(main())
    except Exception as e:
        print(f"Error: {e}")
    finally:
        print("Exiting...")
        sys.exit()



refactor