This commit is contained in:
Believethehype 2023-11-21 14:22:34 +01:00
parent 645fff6284
commit 7abea2dbcd
8 changed files with 37 additions and 38 deletions

23
dvm.py
View File

@ -64,8 +64,8 @@ class DVM:
keys = self.keys
def handle(self, relay_url, nostr_event):
print(f"[Nostr] Received new NIP90 Job Request from {relay_url}: {nostr_event.as_json()}")
if EventDefinitions.KIND_NIP90_EXTRACT_TEXT <= nostr_event.kind() <= EventDefinitions.KIND_NIP90_GENERIC:
print("[" + self.dvm_config.NIP89.name + "] " + f"Received new NIP90 Job Request from {relay_url}: {nostr_event.as_json()}")
handle_nip90_job_event(nostr_event)
elif nostr_event.kind() == EventDefinitions.KIND_ZAP:
handle_zap(nostr_event)
@ -74,9 +74,7 @@ class DVM:
return
def handle_nip90_job_event(nip90_event):
print(str(self.dvm_config.DB))
user = get_or_add_user(self.dvm_config.DB, nip90_event.pubkey().to_hex())
print("got user")
task_supported, task, duration = check_task_is_supported(nip90_event, client=self.client,
get_duration=(not user.iswhitelisted),
config=self.dvm_config)
@ -84,7 +82,7 @@ class DVM:
if user.isblacklisted:
send_job_status_reaction(nip90_event, "error", client=self.client, config=self.dvm_config)
print("[Nostr] Request by blacklisted user, skipped")
print("[" + self.dvm_config.NIP89.name + "] Request by blacklisted user, skipped")
elif task_supported:
print("Received new Task: " + task)
@ -98,7 +96,7 @@ class DVM:
task_is_free = True
if user.iswhitelisted or task_is_free:
print("[Nostr] Free or Whitelisted for task " + task + ". Starting processing..")
print("[" + self.dvm_config.NIP89.name + "] Free or Whitelisted for task " + task + ". Starting processing..")
send_job_status_reaction(nip90_event, "processing", True, 0, client=self.client,
config=self.dvm_config)
do_work(nip90_event, is_from_bot=False)
@ -109,7 +107,7 @@ class DVM:
if tag.as_vec()[0] == 'bid':
bid = int(tag.as_vec()[1])
print("[Nostr][Payment required] New Nostr " + task + " Job event: " + nip90_event.as_json())
print("[" + self.dvm_config.NIP89.name + "] Payment required: New Nostr " + task + " Job event: " + nip90_event.as_json())
if bid > 0:
bid_offer = int(bid / 1000)
if bid_offer >= amount:
@ -118,7 +116,7 @@ class DVM:
client=self.client, config=self.dvm_config)
else: # If there is no bid, just request server rate from user
print("[Nostr] Requesting payment for Event: " + nip90_event.id().to_hex())
print("[" + self.dvm_config.NIP89.name + "] Requesting payment for Event: " + nip90_event.id().to_hex())
send_job_status_reaction(nip90_event, "payment-required",
False, amount, client=self.client, config=self.dvm_config)
else:
@ -177,7 +175,7 @@ class DVM:
config=self.dvm_config)
if job_event is not None and task_supported:
if amount <= invoice_amount:
print("[Nostr] Payment-request fulfilled...")
print("[" + self.dvm_config.NIP89.name + "] Payment-request fulfilled...")
send_job_status_reaction(job_event, "processing", client=self.client,
config=self.dvm_config)
indices = [i for i, x in enumerate(self.job_list) if
@ -204,7 +202,7 @@ class DVM:
send_job_status_reaction(job_event, "payment-rejected",
False, invoice_amount, client=self.client,
config=self.dvm_config)
print("[Nostr] Invoice was not paid sufficiently")
print("[" + self.dvm_config.NIP89.name + "] Invoice was not paid sufficiently")
elif zapped_event.kind() in EventDefinitions.ANY_RESULT:
print("Someone zapped the result of an exisiting Task. Nice")
@ -302,7 +300,7 @@ class DVM:
response_kind = originalevent.kind() + 1000
event = EventBuilder(response_kind, str(content), replytags).to_event(key)
send_event(event, key=key)
print("[Nostr] " + str(response_kind) + " Job Response event sent: " + event.as_json())
print("[" + self.dvm_config.NIP89.name + "] " + str(response_kind) + " Job Response event sent: " + event.as_json())
return event.as_json()
def respond_to_error(content, originaleventstr, is_from_bot=False, dvm_key=None):
@ -411,7 +409,7 @@ class DVM:
status=status, result="", is_processed=False, bolt11=bolt11,
payment_hash=payment_hash,
expires=expires, from_bot=False))
print(str(self.job_list))
#print(str(self.job_list))
if status == "payment-required" or status == "payment-rejected" or (
status == "processing" and not is_paid) or (
status == "success" and not is_paid):
@ -428,8 +426,7 @@ class DVM:
event = EventBuilder(EventDefinitions.KIND_FEEDBACK, reaction, tags).to_event(keys)
send_event(event, key=keys)
print(
"[Nostr] Sent Kind " + str(
print("[" + self.dvm_config.NIP89.name + "]" + ": Sent Kind " + str(
EventDefinitions.KIND_FEEDBACK) + " Reaction: " + status + " " + event.as_json())
return event.as_json()

View File

@ -18,7 +18,7 @@ Outputs: An url to an Image
class ImageGenerationSDXL(DVMTaskInterface):
NAME: str
NAME: str = ""
KIND: int = EventDefinitions.KIND_NIP90_GENERATE_IMAGE
TASK: str = "text-to-image"
COST: int = 5
@ -109,6 +109,16 @@ class ImageGenerationSDXL(DVMTaskInterface):
prompt = prompt.replace(";", ",")
request_form['data'] = '[{"id":"input_prompt","type":"input","src":"request:text","data":"' + prompt + '","active":"True"},{"id":"negative_prompt","type":"input","src":"request:text","data":"' + negative_prompt + '","active":"True"},{"id":"output_image","type":"output","src":"request:image","active":"True"}]'
request_form['options'] = ('[{"model":" + ' + model
+ '","ratio":"' + str(ratio_width) + ':' + str(ratio_height)
+ '","width":"' + str(width) + ':' + str(height)
+ '","strength":"' + str(strength)
+ '","guidance_scale":"' + str(guidance_scale)
+ '","lora":"' + str(lora)
+ '","lora_weight":"' + str(lora_weight)
+ '"}]')
request_form["optStr"] = ('model=' + model + ';ratio=' + str(ratio_width) + '-' + str(ratio_height) + ';size=' +
str(width) + '-' + str(height) + ';strength=' + str(strength) + ';guidance_scale=' +
str(guidance_scale) + ';lora=' + lora + ';lora_weight=' + lora_weight)

View File

@ -18,7 +18,7 @@ Outputs: Text containing the extracted contents of the PDF file
class TextExtractionPDF(DVMTaskInterface):
NAME: str
NAME: str = ""
KIND: int = EventDefinitions.KIND_NIP90_EXTRACT_TEXT
TASK: str = "pdf-to-text"
COST: int = 20

View File

@ -16,7 +16,7 @@ Outputs: Text containing the Translation in the desired language.
class Translation(DVMTaskInterface):
NAME: str
NAME: str = ""
KIND: int = EventDefinitions.KIND_NIP90_TRANSLATE_TEXT
TASK: str = "translation"
COST: int = 0

View File

@ -83,10 +83,8 @@ def nostr_client():
client.subscribe([dm_zap_filter, dvm_filter])
# nostr_client_test_translation("This is the result of the DVM in spanish", "text", "es", 20, 20)
#nostr_client_test_translation("44a0a8b395ade39d46b9d20038b3f0c8a11168e67c442e3ece95e4a1703e2beb", "event", "es", 20,
# 20)
# nostr_client_test_translation("9c5d6d054e1b7a34a6a4b26ac59469c96e77f7cba003a30456fa6a57974ea86d", "event", "zh", 20, 20)
#nostr_client_test_translation("note1p8cx2dz5ss5gnk7c59zjydcncx6a754c0hsyakjvnw8xwlm5hymsnc23rs", "event", "es", 20,20)
#nostr_client_test_translation("44a0a8b395ade39d46b9d20038b3f0c8a11168e67c442e3ece95e4a1703e2beb", "event", "zh", 20, 20)
nostr_client_test_image("a beautiful purple ostrich watching the sunset")
class NotificationHandler(HandleNotification):

View File

@ -55,9 +55,7 @@ def check_task_is_supported(event, client, get_duration=False, config=None):
input_value = ""
input_type = ""
duration = 1
task = get_task(event, client=client, dvmconfig=dvm_config)
for tag in event.tags():
if tag.as_vec()[0] == 'i':
if len(tag.as_vec()) < 3:
@ -71,29 +69,28 @@ def check_task_is_supported(event, client, get_duration=False, config=None):
if evt is None:
print("Event not found")
return False, "", 0
elif input_type == 'url' and check_url_is_readable(input_value) is None:
print("Url not readable / supported")
return False, task, duration
elif tag.as_vec()[0] == 'output':
output = tag.as_vec()[1]
if not (
output == "text/plain" or output == "text/json" or output == "json" or output == "image/png" or "image/jpg" or output == ""):
if not (output == "text/plain"
or output == "text/json" or output == "json"
or output == "image/png" or "image/jpg"
or output == "image/png;format=url" or output == "image/jpg;format=url"
or output == ""):
print("Output format not supported, skipping..")
return False, "", 0
task = get_task(event, client=client, dvmconfig=dvm_config)
for dvm in dvm_config.SUPPORTED_TASKS:
if dvm.TASK == task:
if not dvm.is_input_supported(input_type, event.content()):
return False, task, duration
if input_type == 'url' and check_url_is_readable(input_value) is None:
print("url not readable")
return False, task, duration
if task not in (x.TASK for x in dvm_config.SUPPORTED_TASKS):
return False, task, duration
return True, task, duration
@ -121,7 +118,7 @@ def check_url_is_readable(url):
def get_amount_per_task(task, dvm_config, duration=1):
for dvm in dvm_config.SUPPORTED_TASKS:
for dvm in dvm_config.SUPPORTED_TASKS: #this is currently just one
if dvm.TASK == task:
amount = dvm.COST * duration
return amount

View File

@ -58,9 +58,7 @@ def add_sql_table_column(db):
def add_to_sql_table(db, npub, sats, iswhitelisted, isblacklisted, nip05, lud16, name, lastactive):
try:
print("ADD: " + str(db))
con = sqlite3.connect(db)
print("Connected")
cur = con.cursor()
data = (npub, sats, iswhitelisted, isblacklisted, nip05, lud16, name, lastactive)
cur.execute("INSERT or IGNORE INTO users VALUES(?, ?, ?, ?, ?, ?, ?, ?)", data)
@ -94,15 +92,12 @@ def update_sql_table(db, npub, sats, iswhitelisted, isblacklisted, nip05, lud16,
def get_from_sql_table(db, npub):
try:
con = sqlite3.connect(db)
print("Connecting to DB")
cur = con.cursor()
cur.execute("SELECT * FROM users WHERE npub=?", (npub,))
row = cur.fetchone()
con.close()
print(row)
if row is None:
user = None
print("returning None")
return user
else:
user = User

View File

@ -19,6 +19,8 @@ def get_event_by_id(event_id, client=None, config=None):
id_filter = Filter().author(split[1]).custom_tag(Alphabet.D, [split[2]])
events = client.get_events_of([id_filter], timedelta(seconds=config.RELAY_TIMEOUT))
else:
if str(event_id).startswith('note'):
event_id = EventId.from_bech32(event_id).to_hex()
id_filter = Filter().id(event_id).limit(1)
events = client.get_events_of([id_filter], timedelta(seconds=config.RELAY_TIMEOUT))
if is_new_client: