main.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. from urllib.parse import urlparse
  3. import tempfile
  4. import os
  5. import whisper
  6. import simplematrixbotlib as botlib
  7. import nio
  8. model = whisper.load_model("tiny")
  9. creds = botlib.Creds(
  10. homeserver=os.environ['HOMESERVER'],
  11. username=os.environ['USERNAME'],
  12. password=os.getenv('PASSWORD', None),
  13. login_token=os.getenv('LOGIN_TOKEN', None),
  14. access_token=os.getenv('ACCESS_TOKEN', None),
  15. session_stored_file="/data/session.txt"
  16. )
  17. config = botlib.Config()
  18. config.encryption_enabled = True
  19. config.emoji_verify = True
  20. config.ignore_unverified_devices = True
  21. config.store_path = '/data/crypto_store/'
  22. bot = botlib.Bot(creds, config)
  23. @bot.listener.on_custom_event(nio.RoomMessageAudio)
  24. async def on_audio_message(room, event):
  25. print(room.machine_name, event.sender, event.body, event.url)
  26. match = botlib.MessageMatch(room, event, bot)
  27. if match.is_not_from_this_bot():
  28. await bot.async_client.room_typing(room.machine_name, True, timeout=120000)
  29. url = urlparse(event.url)
  30. response = await bot.async_client.download(server_name=url.netloc, media_id=url.path[1:])
  31. print(response)
  32. with tempfile.NamedTemporaryFile("w+b") as file:
  33. file.write(response.body)
  34. file.flush()
  35. result = model.transcribe(file.name)
  36. await bot.async_client.room_typing(room.machine_name, False)
  37. await bot.api.send_text_message(
  38. room_id=room.room_id,
  39. message=f"Transcription of {response.filename}: {result['text']}",
  40. msgtype="m.notice")
  41. bot.run()