main.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 = False
  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_audio_message(room, event):
  24. print(room.machine_name, event.sender, event.body, event.url)
  25. match = botlib.MessageMatch(room, event, bot)
  26. if match.is_not_from_this_bot():
  27. await bot.async_client.room_typing(room.machine_name, True, timeout=120000)
  28. url = urlparse(event.url)
  29. response = await bot.async_client.download(server_name=url.netloc, media_id=url.path[1:])
  30. print(response)
  31. result = await asr.transcribe(response.body)
  32. await bot.async_client.room_typing(room.machine_name, False)
  33. if response.filename:
  34. await bot.api.send_text_message(
  35. room_id=room.room_id,
  36. message=f"Transcription of {response.filename}: {result}",
  37. msgtype="m.notice")
  38. else:
  39. await bot.api.send_text_message(
  40. room_id=room.room_id,
  41. message=f"Transcription: {result}",
  42. msgtype="m.notice")
  43. if __name__ == "__main__":
  44. asr.load_model()
  45. bot.run()