main.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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', os.getenv('PRELOAD_MODEL', 'tiny')), os.getenv('ASR_LANGUAGE', 'en'))
  22. @bot.listener.on_custom_event(nio.RoomMessage)
  23. async def on_message(room, event):
  24. if not isinstance(event, (nio.RoomMessageAudio,
  25. nio.RoomEncryptedAudio,
  26. nio.RoomMessageVideo,
  27. nio.RoomEncryptedVideo)):
  28. return
  29. encrypted = isinstance(event, (nio.RoomEncryptedAudio, nio.RoomEncryptedVideo))
  30. print(room.machine_name, event.sender, event.body, event.url)
  31. match = botlib.MessageMatch(room, event, bot)
  32. if match.is_not_from_this_bot():
  33. await bot.async_client.room_typing(room.machine_name, True, timeout=120000)
  34. url = urlparse(event.url)
  35. response = await bot.async_client.download(server_name=url.netloc, media_id=url.path[1:])
  36. if encrypted:
  37. print("decrypting...")
  38. data = nio.crypto.attachments.decrypt_attachment(
  39. response.body,
  40. event.source["content"]["file"]["key"]["k"],
  41. event.source["content"]["file"]["hashes"]["sha256"],
  42. event.source["content"]["file"]["iv"],
  43. )
  44. else:
  45. data = response.body
  46. print(response)
  47. result = await asr.transcribe(data)
  48. await bot.async_client.room_typing(room.machine_name, False)
  49. if not result:
  50. print("No result")
  51. return
  52. filename = response.filename or event.body
  53. if filename:
  54. reply = f"Transcription of {filename}: {result}"
  55. else:
  56. reply = f"Transcription: {result}"
  57. await bot.api._send_room(
  58. room_id=room.room_id,
  59. content={
  60. "msgtype": "m.notice",
  61. "body": reply,
  62. "m.relates_to": {
  63. "m.in_reply_to": {
  64. "event_id": event.event_id
  65. }
  66. }
  67. })
  68. if __name__ == "__main__":
  69. asr.load_model()
  70. bot.run()