main.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python3
  2. from urllib.parse import urlparse
  3. import os
  4. import simplematrixbotlib as botlib
  5. import nio
  6. from speech_recognition import ASR
  7. creds = botlib.Creds(
  8. homeserver=os.environ['HOMESERVER'],
  9. username=os.environ['USERNAME'],
  10. password=os.getenv('PASSWORD', None),
  11. login_token=os.getenv('LOGIN_TOKEN', None),
  12. access_token=os.getenv('ACCESS_TOKEN', None),
  13. session_stored_file="/data/session.txt"
  14. )
  15. config = botlib.Config()
  16. config.encryption_enabled = True
  17. config.emoji_verify = False
  18. config.ignore_unverified_devices = True
  19. config.store_path = '/data/crypto_store/'
  20. bot = botlib.Bot(creds, config)
  21. asr = ASR(os.getenv('ASR_MODEL', 'tiny'))
  22. @bot.listener.on_custom_event(nio.RoomMessageAudio)
  23. async def on_message_audio(room, event):
  24. await on_audio(room, event, False)
  25. @bot.listener.on_custom_event(nio.RoomEncryptedAudio)
  26. async def on_encrypted_audio(room, event):
  27. await on_audio(room, event, True)
  28. async def on_audio(room, event, encrypted):
  29. print(room.machine_name, event.sender, event.body, event.url)
  30. match = botlib.MessageMatch(room, event, bot)
  31. if match.is_not_from_this_bot():
  32. await bot.async_client.room_typing(room.machine_name, True, timeout=120000)
  33. url = urlparse(event.url)
  34. response = await bot.async_client.download(server_name=url.netloc, media_id=url.path[1:])
  35. if encrypted:
  36. print("decrypting...")
  37. data = nio.crypto.attachments.decrypt_attachment(
  38. response.body,
  39. event.source["content"]["file"]["key"]["k"],
  40. event.source["content"]["file"]["hashes"]["sha256"],
  41. event.source["content"]["file"]["iv"],
  42. )
  43. else:
  44. data = response.body
  45. print(response)
  46. result = await asr.transcribe(data)
  47. await bot.async_client.room_typing(room.machine_name, False)
  48. if response.filename:
  49. await bot.api.send_text_message(
  50. room_id=room.room_id,
  51. message=f"Transcription of {response.filename}: {result}",
  52. msgtype="m.notice")
  53. else:
  54. await bot.api.send_text_message(
  55. room_id=room.room_id,
  56. message=f"Transcription: {result}",
  57. msgtype="m.notice")
  58. if __name__ == "__main__":
  59. asr.load_model()
  60. bot.run()