Ola gente dia a todos gostaria da opinião de vocês pra saber qual o melhor ou qual protocolos vocês usam ou preferem para conversa com amigos ou familiares?? Atualmente estou usando o xmpp q é meu preferido mas cheguei a testar o matrix e achei bem interessante os apps moderno e as opções de pontes. Vocês acham q matrix está maduro suficiente pras coisas q mencionei ali em cima ou melhor ficar com xmpp?

Obs: talvez se eu fosse usar matrix iria auto hospedar ele pra usar e tals

  • thes0ls@lemmy.eco.br
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    3 months ago

    Welp que eu acabei mesmo passando a limpo o meu script.


    Aqui estou levando em conta que o matrix já está com a bridge rodando e o script vai cuidar só de espiar se chega mensagem de áudio.

    Quem for usar, leia o código que eu botei uns comentários nos trechos que deve editar.

    Testei só no meu próprio ambiente, então pode ser que tenha uma dependência ou outra que esqueci de anotar (nem lembro como que instalei o whisper, por exemplo).

    A documentação do nio fica em aqui: https://matrix-nio.readthedocs.io/en/latest/index.html


    # -*- coding: utf-8 -*-
    
    
    import requests
    
    import os
    import re
    import time
    
    import whisper
    
    import asyncio
    import json
    
    from nio import AsyncClient, MatrixRoom, RoomMessageText, RoomMessageAudio, Api
    
    # whisper requer o ffmpeg:
    # sudo apt update && sudo apt install ffmpeg
    
    # E no virtualenv do seu python, os requisitos provavelmente são:
    # pip install asyncio openai-whisper matrix-nio
    
    # Analisar o restante do script e substituir os valores do room_id na função audio_callback pelos da sua instância
    
    # ------------------------------------------------
    
    # Credenciais do login. Pegar os dados da response:
    # curl -XPOST -d '{"type":"m.login.password", "user":"NOMEDOUSUARIO", "password":"SENHADOUSUARIO"}' "https://matrix.zzz/_matrix/client/r0/login"
    CONFIG_FILE = "matrix-credentials.json"
    if not os.path.isfile(CONFIG_FILE):
      f = open(CONFIG_FILE, 'w')
      f.write('{"user_id":"@usuario:matrix.zzz","access_token":"abc123","home_server":"https://matrix.zzz","device_id":"ABCD"}')
      f.close()
      print('Preencha as credenciais...')
      exit()
      
    # Este arquivo é usado pro script ignorar mensagens anteriores a data dele
    lastruntime='matrix.time.txt'
    if not os.path.isfile(lastruntime):
      f = open(lastruntime, 'w')
      f.write("0")
      f.close()
    
    # Pasta onde ficarão salvos os áudio temporários
    if not os.path.isdir("matrixtemp"):
        os.mkdir("matrixtemp")
    
    with open(CONFIG_FILE, "r") as f:
        config = json.load(f)
        client = AsyncClient(config["home_server"])
        client.access_token = config["access_token"]
        client.user_id = config["user_id"]
        client.device_id = config["device_id"]
    
    async def matrix_message(text, room_id, server_timestamp, in_reply_to = 0):
        event_type="m.room.message"
        msgtype="m.text"
            
        if in_reply_to == 0:
            content = {
                    "msgtype": msgtype,
                    "body": cleanhtml(text),
                    "format": "org.matrix.custom.html",
                    "formatted_body": text
            }
        else:
            content = {
                    "m.relates_to": {"m.in_reply_to": {"event_id": in_reply_to  }   },
                    "msgtype": msgtype,
                    "body": cleanhtml(text),
                    "format": "org.matrix.custom.html",
                    "formatted_body": text
            }
        
        await client.room_send(
            room_id,
            message_type="m.room.message",
            content=content,
            ignore_unverified_devices=True,
        )
        
        f = open(lastruntime, "w")
        f.write(str(server_timestamp))
        f.close()
        
    
    CLEANR = re.compile('<.*?>') 
    
    def cleanhtml(raw_html):
      cleantext = re.sub(CLEANR, '', raw_html)
      return cleantext
      
    
    async def audio_callback(room: MatrixRoom, event: RoomMessageAudio) -> None:
        # Aqui os chats que podem receber a transcrição na própria conversa.
        # Pra pegar o id, no Element, clique direito na sala, Settings > Advanced > Internal room ID
        permitidos=[
        "!AsasasASas:matrix.zzz",
        "!Idasasas:matrix.zzz"
        ]
        if room.room_id in permitidos:    
            room_id = room.room_id
            event_id = event.event_id
        else:
            room_id = "!BHBhbHBHbhb:matrix.zzz" # Aqui especifica o room_id do chat que vai receber fora dos permitidos acima
            event_id = 0
        
        sender = event.source['sender']
        lastrun = open(lastruntime, "r")
        lastrun = lastrun.read()
        if event.server_timestamp > int(lastrun):
            print(vars(room))
            print(event)
            dllink = Api.mxc_to_http(event.source['content']['url'])
            print(dllink)
            filename = os.path.basename(dllink)+".ogg"
            filepath = "./matrixtemp/"+filename
            
            r = requests.get(dllink)
            
            print(r.status_code)
            
            with open(filepath, 'wb') as f:
                f.write(r.content)
            
            print("iniciando openai/whisper")
            start = time.time()
            model = whisper.load_model("medium")
            
            whisperconfig="bs3" #def p2bs5 bs3 bs2
            
            if whisperconfig == "p2bs5":
                result = model.transcribe(filepath, language="pt", fp16=False, verbose=True, patience=2, beam_size=5) #580 segundos
            if whisperconfig == "def":
                result = model.transcribe(filepath, language="pt", fp16=False, verbose=True) #56 segundos
            if whisperconfig == "bs3":
                result = model.transcribe(filepath, language="pt", fp16=False, verbose=True, beam_size=3) #181 segundos
            if whisperconfig == "bs2":
                result = model.transcribe(filepath, language="pt", fp16=False, verbose=True, beam_size=2) #136 segundos
                
            end = time.time()
            tempogasto = int(end - start)
            print("Conluido, tempo gasto: "+ str(tempogasto))
            text = result["text"]
    
            await matrix_message("<b>Transcrição:</b><br/><br/>"+sender+":<br/> "+text, room_id, str(event.server_timestamp), event_id)
    
    
    
    async def main() -> None:        
        client.add_event_callback(audio_callback, RoomMessageAudio)
        
        await client.sync_forever(timeout=30000)  # milliseconds
    
    
    asyncio.run(main())
    

    EDIT: 2024-03-27 21h50: Corrigi um erro de copicola logo depois do if not os.path.isfile(CONFIG_FILE):.