special key Key.media_play_pause pressed
Recording stopped by user.
Done recording
2023-11-28 05:32:21,577 - INFO - HTTP Request: POST https://api.naga.ac/v1/audio/transcriptions "HTTP/1.1 200 OK"
Jag har lagt in 1,03 kilo.
2023-11-28 05:32:21,578 - ERROR - Task exception was never retrieved
future: <Task finished name='Task-6' coro=<start_recording() done, defined at /home/rickard/Documents/rs232/new copy.py:260> exception=TypeError('expected string or bytes-like object')>
Traceback (most recent call last):
  File "/home/rickard/Documents/rs232/new copy.py", line 262, in start_recording
    await asyncio.gather(
  File "/home/rickard/Documents/rs232/new copy.py", line 253, in record_audio
    extracted_weight = extract_weight(audio_text)
  File "/home/rickard/Documents/rs232/new copy.py", line 223, in extract_weight
    matches = re.findall(pattern, text, re.IGNORECASE)
  File "/usr/lib/python3.10/re.py", line 240, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
hey



# FastAPI endpoint to trigger async start_recording
@app.post("/start_recording")
async def api_start_recording():
    asyncio.create_task(start_recording())
    return {"message": "Started recording asynchronously"}



async def record_audio():
    global adress, stop_recording, transcriber, check_weight
    print("Starting recording…")
    url = f"{adress}/audio.wav"

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            async with aioopen("audio.wav", "wb") as fd:
                async for chunk in response.content.iter_chunked(1024):
                    await fd.write(chunk)
                    # Check if the stop condition is set
                    if stop_recording.is_set():
                        print("Recording stopped by user.")
                        break

    print("Done recording")
    audio_text = transcriber.transcribe_audio("audio.wav")
    await audio_text
    if "lägg in" or "lägga in" or "lagt in" in audio_text:
        check_weight = "In"
        extracted_weight = extract_weight(audio_text)
        await generate_audio(extract_weight, False)
        await update_csv(extracted_weight, check_weight)

    print(audio_text)


async def start_recording():
    stop_recording.clear()
    await asyncio.gather(
        record_audio(),
        schedule_stop()
    )

async def schedule_stop():
    await asyncio.sleep(7)
    if not stop_recording.is_set():
        print("7 seconds passed. Stopping recording.")
        stop_recording.set()

def on_press(key):
    global check_weight, first_boot
    try:
        # pynput.keyboard.KeyCode
        print("hey")
        print(key)
        if key == keyboard.Key.media_next:
            print("heys")
            check_weight = "In"
            asyncio.run(process_images())
            print("Media play/pause key pressed")
        if key == keyboard.Key.media_previous:
            print("heys")
            check_weight = "Out"
            asyncio.run(process_images())
            print("Media play/pause key pressed")
        if key == keyboard.Key.media_play_pause:
            if not stop_recording.is_set() or first_boot:  # If recording has not been stopped yet
                print("Stopping recording early…")
                stop_recording.set()
                first_boot = False
            else:
                print("Starting new recording…")
                # Make an HTTP POST request to FastAPI endpoint to start recording
                requests.post("http://localhost:3333/start_recording")
        print("Alphanumeric key {0} pressed".format(key.char))
        # pynput.keyboard.Key (you can find volume keys here)
        print("Special Key {0} pressed".format(key))
        # set sound up only after 1 key press...
    except AttributeError:
        print("special key {0} pressed".format(key))


from openai import AsyncOpenAI


class Transcriber:
    def __init__(self, api_key, base_url):
        self.client = AsyncOpenAI(
        api_key= api_key,
        base_url=base_url
        )

    async def transcribe_audio(self, audio_file_path):
        audio_file = open("audio.mp3", "rb")
        transcript = await self.client.audio.transcriptions.create(
          model="whisper-1", 
          file=audio_file,
          language="sv",
          prompt="Vi pratar om att lägga in vikter mellan 30-200 kilo"
        )

        print(transcript.text)

        return transcript.text