Skip to content

Commit

Permalink
Merge pull request #28 from believethehype/async_sdk
Browse files Browse the repository at this point in the history
Move to async functions/ nostr sdk 0.32.1
  • Loading branch information
believethehype authored Jun 7, 2024
2 parents f75ca73 + 94aaebd commit 686789e
Show file tree
Hide file tree
Showing 55 changed files with 941 additions and 807 deletions.
36 changes: 19 additions & 17 deletions examples/ollama_dvm/test_client.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import asyncio
import json
import time
from pathlib import Path
from threading import Thread

import dotenv
from nostr_sdk import Keys, Client, NostrSigner, Tag, EventBuilder, Filter, HandleNotification, Timestamp, nip04_decrypt
from nostr_sdk import Keys, Client, NostrSigner, Tag, EventBuilder, Filter, HandleNotification, Timestamp, \
nip04_decrypt, Event

from nostr_dvm.utils.dvmconfig import DVMConfig
from nostr_dvm.utils.nostr_utils import send_event, check_and_set_private_key
from nostr_dvm.utils.definitions import EventDefinitions


def nostr_client_test_llm(prompt):
async def nostr_client_test_llm(prompt):
keys = Keys.parse(check_and_set_private_key("test_client"))

iTag = Tag.parse(["i", prompt, "text"])
Expand All @@ -28,42 +30,42 @@ def nostr_client_test_llm(prompt):
client = Client(signer)

for relay in relay_list:
client.add_relay(relay)
client.connect()
await client.add_relay(relay)
await client.connect()
config = DVMConfig
send_event(event, client=client, dvm_config=config)
await send_event(event, client=client, dvm_config=config)
return event.as_json()

def nostr_client():
async def nostr_client():
keys = Keys.parse(check_and_set_private_key("test_client"))
sk = keys.secret_key()
pk = keys.public_key()
print(f"Nostr Test Client public key: {pk.to_bech32()}, Hex: {pk.to_hex()} ")
client = Client(keys)
dvmconfig = DVMConfig()
for relay in dvmconfig.RELAY_LIST:
client.add_relay(relay)
client.connect()
await client.add_relay(relay)
await client.connect()

dm_zap_filter = Filter().pubkey(pk).kinds([EventDefinitions.KIND_DM,
EventDefinitions.KIND_ZAP]).since(
Timestamp.now()) # events to us specific
dvm_filter = (Filter().kinds([EventDefinitions.KIND_NIP90_RESULT_GENERATE_TEXT,
EventDefinitions.KIND_FEEDBACK]).since(Timestamp.now())) # public events
client.subscribe([dm_zap_filter, dvm_filter])
await client.subscribe([dm_zap_filter, dvm_filter])


nostr_client_test_llm("Tell me a joke about a purple Ostrich!")
await nostr_client_test_llm("Tell me a joke about a purple Ostrich!")
print("Sending Job Request")


#nostr_client_test_image_private("a beautiful ostrich watching the sunset")
class NotificationHandler(HandleNotification):
def handle(self, relay_url, event):
def handle(self, relay_url, subscription_id, event: Event):
print(f"Received new event from {relay_url}: {event.as_json()}")
if event.kind() == 7000:
print("[Nostr Client]: " + event.as_json())
elif 6000 < event.kind() < 6999:
elif 6000 < event.kind().as_u64() < 6999:
print("[Nostr Client]: " + event.as_json())
print("[Nostr Client]: " + event.content())

Expand All @@ -75,12 +77,12 @@ def handle(self, relay_url, event):
print("[Nostr Client]: " + f"Received new zap:")
print(event.as_json())

def handle_msg(self, relay_url, msg):
async def handle_msg(self, relay_url, msg):
return

client.handle_notifications(NotificationHandler())
asyncio.create_task(client.handle_notifications(NotificationHandler()))
while True:
time.sleep(5.0)
await asyncio.sleep(5.0)


if __name__ == '__main__':
Expand All @@ -92,5 +94,5 @@ def handle_msg(self, relay_url, msg):
else:
raise FileNotFoundError(f'.env file not found at {env_path} ')

nostr_dvm_thread = Thread(target=nostr_client())
nostr_dvm_thread.start()
asyncio.run(nostr_client())

24 changes: 12 additions & 12 deletions examples/tts_dvm/test_client.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import asyncio
import json
import time
from pathlib import Path
from threading import Thread

import dotenv
from nostr_sdk import Keys, Client, Tag, EventBuilder, Filter, HandleNotification, Timestamp, nip04_decrypt, \
NostrSigner
NostrSigner, Event

from nostr_dvm.utils.dvmconfig import DVMConfig
from nostr_dvm.utils.nostr_utils import send_event, check_and_set_private_key
Expand Down Expand Up @@ -39,7 +40,7 @@ def nostr_client_test_tts(prompt):
send_event(event, client=client, dvm_config=config)
return event.as_json()

def nostr_client():
async def nostr_client():
keys = Keys.parse(check_and_set_private_key("test_client"))
sk = keys.secret_key()
pk = keys.public_key()
Expand All @@ -49,15 +50,15 @@ def nostr_client():

dvmconfig = DVMConfig()
for relay in dvmconfig.RELAY_LIST:
client.add_relay(relay)
client.connect()
await client.add_relay(relay)
await client.connect()

dm_zap_filter = Filter().pubkey(pk).kinds([EventDefinitions.KIND_DM,
EventDefinitions.KIND_ZAP]).since(
Timestamp.now()) # events to us specific
dvm_filter = (Filter().kinds([EventDefinitions.KIND_NIP90_RESULT_TEXT_TO_SPEECH,
EventDefinitions.KIND_FEEDBACK]).since(Timestamp.now())) # public events
client.subscribe([dm_zap_filter, dvm_filter])
await client.subscribe([dm_zap_filter, dvm_filter])


nostr_client_test_tts("Hello, this is a test. Mic check one, two.")
Expand All @@ -66,11 +67,11 @@ def nostr_client():

#nostr_client_test_image_private("a beautiful ostrich watching the sunset")
class NotificationHandler(HandleNotification):
def handle(self, relay_url, event):
def handle(self, relay_url, subscription_id, event: Event):
print(f"Received new event from {relay_url}: {event.as_json()}")
if event.kind() == 7000:
print("[Nostr Client]: " + event.as_json())
elif 6000 < event.kind() < 6999:
elif 6000 < event.kind().as_u64() < 6999:
print("[Nostr Client]: " + event.as_json())
print("[Nostr Client]: " + event.content())

Expand All @@ -82,12 +83,12 @@ def handle(self, relay_url, event):
print("[Nostr Client]: " + f"Received new zap:")
print(event.as_json())

def handle_msg(self, relay_url, msg):
async def handle_msg(self, relay_url, msg):
return

client.handle_notifications(NotificationHandler())
asyncio.create_task(client.handle_notifications(NotificationHandler()))
while True:
time.sleep(5.0)
await asyncio.sleep(5.0)


if __name__ == '__main__':
Expand All @@ -99,5 +100,4 @@ def handle_msg(self, relay_url, msg):
else:
raise FileNotFoundError(f'.env file not found at {env_path} ')

nostr_dvm_thread = Thread(target=nostr_client())
nostr_dvm_thread.start()
asyncio.run(nostr_client())
33 changes: 17 additions & 16 deletions examples/unleashed_dvm/test_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import json
import time
from datetime import timedelta
Expand All @@ -6,14 +7,14 @@

import dotenv
from nostr_sdk import Keys, Client, Tag, EventBuilder, Filter, HandleNotification, Timestamp, nip04_decrypt, \
NostrSigner, Options
NostrSigner, Options, Event

from nostr_dvm.utils.dvmconfig import DVMConfig
from nostr_dvm.utils.nostr_utils import send_event, check_and_set_private_key
from nostr_dvm.utils.definitions import EventDefinitions


def nostr_client_test(prompt):
async def nostr_client_test(prompt):
keys = Keys.parse(check_and_set_private_key("test_client"))

iTag = Tag.parse(["i", prompt, "text"])
Expand All @@ -32,13 +33,13 @@ def nostr_client_test(prompt):
signer = NostrSigner.keys(keys)
client = Client.with_opts(signer,opts)
for relay in relay_list:
client.add_relay(relay)
client.connect()
await client.add_relay(relay)
await client.connect()
config = DVMConfig
send_event(event, client=client, dvm_config=config)
await send_event(event, client=client, dvm_config=config)
return event.as_json()

def nostr_client():
async def nostr_client():
keys = Keys.parse(check_and_set_private_key("test_client"))
sk = keys.secret_key()
pk = keys.public_key()
Expand All @@ -48,28 +49,28 @@ def nostr_client():

dvmconfig = DVMConfig()
for relay in dvmconfig.RELAY_LIST:
client.add_relay(relay)
client.connect()
await client.add_relay(relay)
await client.connect()

dm_zap_filter = Filter().pubkey(pk).kinds([EventDefinitions.KIND_DM,
EventDefinitions.KIND_ZAP]).since(
Timestamp.now()) # events to us specific
dvm_filter = (Filter().kinds([EventDefinitions.KIND_NIP90_RESULT_GENERATE_TEXT,
EventDefinitions.KIND_FEEDBACK]).since(Timestamp.now())) # public events
client.subscribe([dm_zap_filter, dvm_filter])
await client.subscribe([dm_zap_filter, dvm_filter])


#nostr_client_test("What has Pablo been up to?")
nostr_client_test("What is Gigi talking about recently?")
await nostr_client_test("What is Gigi talking about recently?")
print("Sending Job Request")


class NotificationHandler(HandleNotification):
def handle(self, relay_url, event):
def handle(self, relay_url, subscription_id, event: Event):
print(f"Received new event from {relay_url}: {event.as_json()}")
if event.kind() == 7000:
print("[Nostr Client]: " + event.as_json())
elif 6000 < event.kind() < 6999:
elif 6000 < event.kind().as_u64() < 6999:
print("[Nostr Client " + event.author().to_bech32() + "]: " + event.as_json())
print("[Nostr Client " + event.author().to_bech32() + "]: " + event.content())

Expand All @@ -85,9 +86,10 @@ def handle(self, relay_url, event):
def handle_msg(self, relay_url, msg):
return

client.handle_notifications(NotificationHandler())
asyncio.create_task(client.handle_notifications(NotificationHandler()))

while True:
time.sleep(1)
await asyncio.sleep(1)


if __name__ == '__main__':
Expand All @@ -99,5 +101,4 @@ def handle_msg(self, relay_url, msg):
else:
raise FileNotFoundError(f'.env file not found at {env_path} ')

nostr_dvm_thread = Thread(target=nostr_client())
nostr_dvm_thread.start()
asyncio.run(nostr_client())
5 changes: 4 additions & 1 deletion nostr_dvm/backends/nova_server/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import io
import json
import os
Expand Down Expand Up @@ -32,6 +33,7 @@ def send_request_to_server(request_form, address):


def send_file_to_server(filepath, address):
result = ""
print("Sending file to Server")
url = ('http://' + address + '/upload')
try:
Expand Down Expand Up @@ -72,7 +74,8 @@ def check_server_status(jobID, address) -> str | pd.DataFrame:
if log != "":
print(log)
# WAITING = 0, RUNNING = 1, FINISHED = 2, ERROR = 3
time.sleep(1.0)
asyncio.sleep(1.0)


if status == 2:
try:
Expand Down
Loading

0 comments on commit 686789e

Please sign in to comment.