main.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env python3
  2. from urllib.parse import urlparse
  3. import os
  4. import time
  5. import asyncio
  6. import simplematrixbotlib as botlib
  7. import nio
  8. from speech_recognition import ASR
  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 = False
  20. config.ignore_unverified_devices = True
  21. config.store_path = '/data/crypto_store/'
  22. bot = botlib.Bot(creds, config)
  23. asr = ASR(os.getenv('ASR_MODEL', os.getenv('PRELOAD_MODEL', 'tiny')), os.getenv('ASR_LANGUAGE', 'en'))
  24. @bot.listener.on_custom_event(nio.RoomMessage)
  25. async def on_message(room, event):
  26. if not isinstance(event, (nio.RoomMessageAudio,
  27. nio.RoomEncryptedAudio,
  28. nio.RoomMessageVideo,
  29. nio.RoomEncryptedVideo)):
  30. return
  31. encrypted = isinstance(event, (nio.RoomEncryptedAudio, nio.RoomEncryptedVideo))
  32. print(room.machine_name, event.sender, event.body, event.url)
  33. match = botlib.MessageMatch(room, event, bot)
  34. if match.is_not_from_this_bot():
  35. await bot.async_client.room_typing(room.machine_name, True, timeout=120000)
  36. url = urlparse(event.url)
  37. response = await bot.async_client.download(server_name=url.netloc, media_id=url.path[1:])
  38. if encrypted:
  39. print("decrypting...")
  40. data = nio.crypto.attachments.decrypt_attachment(
  41. response.body,
  42. event.source["content"]["file"]["key"]["k"],
  43. event.source["content"]["file"]["hashes"]["sha256"],
  44. event.source["content"]["file"]["iv"],
  45. )
  46. else:
  47. data = response.body
  48. print(response)
  49. result = await asr.transcribe(data)
  50. await bot.async_client.room_typing(room.machine_name, False)
  51. if not result:
  52. print("No result")
  53. return
  54. filename = response.filename or event.body
  55. if filename:
  56. reply = f"Transcription of {filename}: {result}"
  57. else:
  58. reply = f"Transcription: {result}"
  59. await bot.api._send_room(
  60. room_id=room.room_id,
  61. content={
  62. "msgtype": "m.notice",
  63. "body": reply,
  64. "m.relates_to": {
  65. "m.in_reply_to": {
  66. "event_id": event.event_id
  67. }
  68. }
  69. })
  70. if __name__ == "__main__":
  71. asr.load_model()
  72. try:
  73. bot.run()
  74. except asyncio.exceptions.TimeoutError as e:
  75. print(e)
  76. print("Timeout, restarting...")
  77. time.sleep(5)