mirror of
https://github.com/believethehype/nostrdvm.git
synced 2025-04-10 04:39:16 +02:00
add currently popular gallery entries dvm
This commit is contained in:
parent
8b18b24615
commit
6255dacac8
18
.idea/dataSources.xml
generated
18
.idea/dataSources.xml
generated
@ -20,11 +20,11 @@
|
||||
</library>
|
||||
</libraries>
|
||||
</data-source>
|
||||
<data-source source="LOCAL" name="Dall-E 3" uuid="7914fe2c-114f-4e86-8ddb-7883b17e9302">
|
||||
<data-source source="LOCAL" name="subscriptions" uuid="7914fe2c-114f-4e86-8ddb-7883b17e9302">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/db/Dall-E 3.db</jdbc-url>
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/db/subscriptions.db</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
<libraries>
|
||||
<library>
|
||||
@ -113,5 +113,19 @@
|
||||
</library>
|
||||
</libraries>
|
||||
</data-source>
|
||||
<data-source source="LOCAL" name="identifier.sqlite [5]" uuid="895f96af-5d9c-42ab-bc9e-3a1abd133e28">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:identifier.sqlite</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
<data-source source="LOCAL" name="identifier.sqlite [4]" uuid="fde56653-f87f-4b4f-9397-66a8d98a0cfe">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:identifier.sqlite</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
388
nostr_dvm/tasks/content_discovery_currently_popular_gallery.py
Normal file
388
nostr_dvm/tasks/content_discovery_currently_popular_gallery.py
Normal file
@ -0,0 +1,388 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from nostr_sdk import Client, Timestamp, PublicKey, Tag, Keys, Options, SecretKey, NostrSigner, NostrDatabase, \
|
||||
ClientBuilder, Filter, NegentropyOptions, NegentropyDirection, init_logger, LogLevel, Event, EventId, Kind, \
|
||||
RelayOptions, RelayLimits
|
||||
|
||||
from nostr_dvm.interfaces.dvmtaskinterface import DVMTaskInterface, process_venv
|
||||
from nostr_dvm.utils import definitions
|
||||
from nostr_dvm.utils.admin_utils import AdminConfig
|
||||
from nostr_dvm.utils.definitions import EventDefinitions
|
||||
from nostr_dvm.utils.dvmconfig import DVMConfig, build_default_config
|
||||
from nostr_dvm.utils.nip88_utils import NIP88Config, check_and_set_d_tag_nip88, check_and_set_tiereventid_nip88
|
||||
from nostr_dvm.utils.nip89_utils import NIP89Config, check_and_set_d_tag, create_amount_tag
|
||||
from nostr_dvm.utils.output_utils import post_process_list_to_events
|
||||
|
||||
|
||||
"""
|
||||
This File contains a Module to discover popular notes
|
||||
Accepted Inputs: none
|
||||
Outputs: A list of events
|
||||
Params: None
|
||||
"""
|
||||
|
||||
|
||||
class DicoverContentCurrentlyPopularGallery(DVMTaskInterface):
|
||||
KIND: Kind = EventDefinitions.KIND_NIP90_VISUAL_DISCOVERY
|
||||
TASK: str = "discover-visuals"
|
||||
FIX_COST: float = 0
|
||||
dvm_config: DVMConfig
|
||||
request_form = None
|
||||
last_schedule: int
|
||||
db_since = 3600
|
||||
db_name = "db/nostr_recent_gallery.db"
|
||||
generic_db_name = "db/nostr_recent_notes.db"
|
||||
min_reactions = 2
|
||||
personalized = False
|
||||
result = ""
|
||||
|
||||
async def init_dvm(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None,
|
||||
admin_config: AdminConfig = None, options=None):
|
||||
|
||||
dvm_config.SCRIPT = os.path.abspath(__file__)
|
||||
self.request_form = {"jobID": "generic"}
|
||||
opts = {
|
||||
"max_results": 200,
|
||||
}
|
||||
self.request_form['options'] = json.dumps(opts)
|
||||
|
||||
self.last_schedule = Timestamp.now().as_secs()
|
||||
|
||||
if self.options.get("db_name"):
|
||||
self.db_name = self.options.get("db_name")
|
||||
if self.options.get("generic_db_name"):
|
||||
self.generic_db_name = self.options.get("generic_db_name")
|
||||
if self.options.get("db_since"):
|
||||
self.db_since = int(self.options.get("db_since"))
|
||||
|
||||
use_logger = False
|
||||
if use_logger:
|
||||
init_logger(LogLevel.DEBUG)
|
||||
|
||||
if self.dvm_config.UPDATE_DATABASE:
|
||||
await self.sync_db()
|
||||
if not self.personalized:
|
||||
self.result = await self.calculate_result(self.request_form)
|
||||
|
||||
async def is_input_supported(self, tags, client=None, dvm_config=None):
|
||||
for tag in tags:
|
||||
if tag.as_vec()[0] == 'i':
|
||||
input_value = tag.as_vec()[1]
|
||||
input_type = tag.as_vec()[2]
|
||||
if input_type != "text":
|
||||
return False
|
||||
return True
|
||||
|
||||
async def create_request_from_nostr_event(self, event, client=None, dvm_config=None):
|
||||
self.dvm_config = dvm_config
|
||||
|
||||
request_form = {"jobID": event.id().to_hex()}
|
||||
|
||||
# default values
|
||||
search = ""
|
||||
max_results = 200
|
||||
|
||||
for tag in event.tags():
|
||||
if tag.as_vec()[0] == 'i':
|
||||
input_type = tag.as_vec()[2]
|
||||
elif tag.as_vec()[0] == 'param':
|
||||
param = tag.as_vec()[1]
|
||||
if param == "max_results": # check for param type
|
||||
max_results = int(tag.as_vec()[2])
|
||||
|
||||
options = {
|
||||
"max_results": max_results,
|
||||
}
|
||||
request_form['options'] = json.dumps(options)
|
||||
return request_form
|
||||
|
||||
async def process(self, request_form):
|
||||
# if the dvm supports individual results, recalculate it every time for the request
|
||||
if self.personalized:
|
||||
return await self.calculate_result(request_form)
|
||||
# else return the result that gets updated once every schenduled update. In this case on database update.
|
||||
else:
|
||||
return self.result
|
||||
|
||||
async def calculate_result(self, request_form):
|
||||
from nostr_sdk import Filter
|
||||
from types import SimpleNamespace
|
||||
ns = SimpleNamespace()
|
||||
|
||||
options = self.set_options(request_form)
|
||||
databasegallery = await NostrDatabase.sqlite(self.db_name)
|
||||
|
||||
timestamp_since = Timestamp.now().as_secs() - self.db_since
|
||||
since = Timestamp.from_secs(timestamp_since)
|
||||
|
||||
filter1 = Filter().kind(definitions.EventDefinitions.KIND_NIP93_GALLERYENTRY).since(since)
|
||||
|
||||
|
||||
ge_events = await databasegallery.query([filter1])
|
||||
if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value:
|
||||
print("[" + self.dvm_config.NIP89.NAME + "] Considering " + str(len(ge_events)) + " Events")
|
||||
ns.finallist = {}
|
||||
|
||||
ids = []
|
||||
relays = []
|
||||
|
||||
if len(ge_events) == 0:
|
||||
return[]
|
||||
|
||||
for ge_event in ge_events:
|
||||
|
||||
id = None
|
||||
for tag in ge_event.tags():
|
||||
if tag.as_vec()[0] == "e":
|
||||
id = EventId.from_hex(tag.as_vec()[1])
|
||||
ids.append(id)
|
||||
if len(tag.as_vec()) > 2:
|
||||
if (tag.as_vec()[2]) not in relays:
|
||||
relays.append(tag.as_vec()[2])
|
||||
|
||||
if id is None:
|
||||
print("No event id found")
|
||||
continue
|
||||
else:
|
||||
print(id.to_hex())
|
||||
|
||||
relaylimits = RelayLimits.disable()
|
||||
opts = (Options().wait_for_send(True).send_timeout(
|
||||
timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)).relay_limits(relaylimits))
|
||||
sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY)
|
||||
keys = Keys.parse(sk.to_hex())
|
||||
signer = NostrSigner.keys(keys)
|
||||
|
||||
cli = ClientBuilder().database(databasegallery).signer(signer).opts(opts).build()
|
||||
for relay in relays:
|
||||
await cli.add_relay(relay)
|
||||
|
||||
await cli.add_relay("wss://relay.damus.io")
|
||||
await cli.add_relay("wss://relay.primal.net")
|
||||
await cli.add_relay("wss://nostr.mom")
|
||||
|
||||
await cli.connect()
|
||||
|
||||
filtreactions = Filter().kinds([definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REPOST,
|
||||
definitions.EventDefinitions.KIND_REACTION,
|
||||
definitions.EventDefinitions.KIND_NOTE]).events(ids).since(since)
|
||||
|
||||
dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN)
|
||||
await cli.reconcile(filtreactions, dbopts)
|
||||
|
||||
|
||||
filter2 = Filter().ids(ids)
|
||||
events = await cli.get_events_of([filter2], timedelta(seconds=self.dvm_config.RELAY_TIMEOUT))
|
||||
|
||||
print(len(events))
|
||||
|
||||
|
||||
for event in events:
|
||||
if event.created_at().as_secs() > timestamp_since:
|
||||
filt = Filter().kinds([definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REPOST,
|
||||
definitions.EventDefinitions.KIND_REACTION,
|
||||
definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(since)
|
||||
reactions = await databasegallery.query([filt])
|
||||
|
||||
if len(reactions) >= self.min_reactions:
|
||||
found = False
|
||||
for ge_event in ge_events:
|
||||
for tag in ge_event.tags():
|
||||
if tag.as_vec()[0] == "e":
|
||||
if event.id().to_hex() == tag.as_vec()[1]:
|
||||
ns.finallist[ge_event.id().to_hex()] = len(reactions)
|
||||
found = True
|
||||
break
|
||||
if found:
|
||||
break
|
||||
|
||||
if len(ns.finallist) == 0:
|
||||
return self.result
|
||||
|
||||
result_list = []
|
||||
finallist_sorted = sorted(ns.finallist.items(), key=lambda x: x[1], reverse=True)[:int(options["max_results"])]
|
||||
for entry in finallist_sorted:
|
||||
# print(EventId.parse(entry[0]).to_bech32() + "/" + EventId.parse(entry[0]).to_hex() + ": " + str(entry[1]))
|
||||
e_tag = Tag.parse(["e", entry[0]])
|
||||
result_list.append(e_tag.as_vec())
|
||||
if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value:
|
||||
print("[" + self.dvm_config.NIP89.NAME + "] Filtered " + str(
|
||||
len(result_list)) + " fitting events.")
|
||||
# await cli.shutdown()
|
||||
return json.dumps(result_list)
|
||||
|
||||
|
||||
async def post_process(self, result, event):
|
||||
"""Overwrite the interface function to return a social client readable format, if requested"""
|
||||
for tag in event.tags():
|
||||
if tag.as_vec()[0] == 'output':
|
||||
format = tag.as_vec()[1]
|
||||
if format == "text/plain": # check for output type
|
||||
result = post_process_list_to_events(result)
|
||||
|
||||
# if not text/plain, don't post-process
|
||||
return result
|
||||
|
||||
async def schedule(self, dvm_config):
|
||||
if dvm_config.SCHEDULE_UPDATES_SECONDS == 0:
|
||||
return 0
|
||||
else:
|
||||
if Timestamp.now().as_secs() >= self.last_schedule + dvm_config.SCHEDULE_UPDATES_SECONDS:
|
||||
if self.dvm_config.UPDATE_DATABASE:
|
||||
await self.sync_db()
|
||||
self.last_schedule = Timestamp.now().as_secs()
|
||||
self.result = await self.calculate_result(self.request_form)
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
|
||||
async def sync_db(self):
|
||||
opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_LONG_TIMEOUT)))
|
||||
sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY)
|
||||
keys = Keys.parse(sk.to_hex())
|
||||
signer = NostrSigner.keys(keys)
|
||||
database = await NostrDatabase.sqlite(self.db_name)
|
||||
cli = ClientBuilder().signer(signer).database(database).opts(opts).build()
|
||||
|
||||
for relay in self.dvm_config.RECONCILE_DB_RELAY_LIST:
|
||||
await cli.add_relay(relay)
|
||||
|
||||
await cli.connect()
|
||||
|
||||
timestamp_since = Timestamp.now().as_secs() - self.db_since
|
||||
since = Timestamp.from_secs(timestamp_since)
|
||||
|
||||
filter1 = Filter().kinds([definitions.EventDefinitions.KIND_NIP93_GALLERYENTRY]).since(since) # Notes, reactions, zaps
|
||||
|
||||
# filter = Filter().author(keys.public_key())
|
||||
if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value:
|
||||
print("[" + self.dvm_config.NIP89.NAME + "] Syncing notes of the last " + str(
|
||||
self.db_since) + " seconds.. this might take a while..")
|
||||
dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN)
|
||||
await cli.reconcile(filter1, dbopts)
|
||||
await cli.database().delete(Filter().until(Timestamp.from_secs(
|
||||
Timestamp.now().as_secs() - self.db_since))) # Clear old events so db doesn't get too full.
|
||||
await cli.shutdown()
|
||||
if self.dvm_config.LOGLEVEL.value >= LogLevel.DEBUG.value:
|
||||
print(
|
||||
"[" + self.dvm_config.NIP89.NAME + "] Done Syncing Notes of the last " + str(self.db_since) + " seconds..")
|
||||
|
||||
|
||||
# We build an example here that we can call by either calling this file directly from the main directory,
|
||||
# or by adding it to our playground. You can call the example and adjust it to your needs or redefine it in the
|
||||
# playground or elsewhere
|
||||
def build_example(name, identifier, admin_config, options, cost=0, update_rate=180, processing_msg=None,
|
||||
update_db=True):
|
||||
dvm_config = build_default_config(identifier)
|
||||
dvm_config.USE_OWN_VENV = False
|
||||
dvm_config.SHOWLOG = True
|
||||
dvm_config.SCHEDULE_UPDATES_SECONDS = update_rate # Every 10 minutes
|
||||
dvm_config.UPDATE_DATABASE = update_db
|
||||
# Activate these to use a subscription based model instead
|
||||
# dvm_config.SUBSCRIPTION_REQUIRED = True
|
||||
# dvm_config.SUBSCRIPTION_DAILY_COST = 1
|
||||
dvm_config.FIX_COST = cost
|
||||
dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg
|
||||
admin_config.LUD16 = dvm_config.LN_ADDRESS
|
||||
|
||||
image = "https://image.nostr.build/b29b6ec4bf9b6184f69d33cb44862db0d90a2dd9a506532e7ba5698af7d36210.jpg",
|
||||
|
||||
# Add NIP89
|
||||
nip89info = {
|
||||
"name": name,
|
||||
"image": image,
|
||||
"picture": image,
|
||||
"about": "I show notes that are currently popular",
|
||||
"lud16": dvm_config.LN_ADDRESS,
|
||||
"encryptionSupported": True,
|
||||
"cashuAccepted": True,
|
||||
"personalized": False,
|
||||
"amount": create_amount_tag(cost),
|
||||
"nip90Params": {
|
||||
"max_results": {
|
||||
"required": False,
|
||||
"values": [],
|
||||
"description": "The number of maximum results to return (default currently 100)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nip89config = NIP89Config()
|
||||
nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"])
|
||||
nip89config.CONTENT = json.dumps(nip89info)
|
||||
|
||||
# admin_config.UPDATE_PROFILE = False
|
||||
# admin_config.REBROADCAST_NIP89 = False
|
||||
|
||||
return DicoverContentCurrentlyPopularGallery(name=name, dvm_config=dvm_config, nip89config=nip89config,
|
||||
admin_config=admin_config, options=options)
|
||||
|
||||
|
||||
def build_example_subscription(name, identifier, admin_config, options, update_rate=180, processing_msg=None,
|
||||
update_db=True):
|
||||
dvm_config = build_default_config(identifier)
|
||||
dvm_config.USE_OWN_VENV = False
|
||||
dvm_config.SHOWLOG = True
|
||||
dvm_config.SCHEDULE_UPDATES_SECONDS = update_rate # Every 3 minutes
|
||||
dvm_config.UPDATE_DATABASE = update_db
|
||||
# Activate these to use a subscription based model instead
|
||||
# dvm_config.SUBSCRIPTION_DAILY_COST = 1
|
||||
dvm_config.FIX_COST = 0
|
||||
dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg
|
||||
admin_config.LUD16 = dvm_config.LN_ADDRESS
|
||||
|
||||
image = "https://image.nostr.build/b29b6ec4bf9b6184f69d33cb44862db0d90a2dd9a506532e7ba5698af7d36210.jpg",
|
||||
# Add NIP89
|
||||
nip89info = {
|
||||
"name": name,
|
||||
"image": image,
|
||||
"picture": image,
|
||||
"about": "I show notes that are currently popular all over Nostr. I'm also used for testing subscriptions.",
|
||||
"lud16": dvm_config.LN_ADDRESS,
|
||||
"encryptionSupported": True,
|
||||
"cashuAccepted": True,
|
||||
"subscription": True,
|
||||
"personalized": False,
|
||||
"nip90Params": {
|
||||
"max_results": {
|
||||
"required": False,
|
||||
"values": [],
|
||||
"description": "The number of maximum results to return (default currently 100)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nip89config = NIP89Config()
|
||||
nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"])
|
||||
nip89config.CONTENT = json.dumps(nip89info)
|
||||
|
||||
nip88config = NIP88Config()
|
||||
nip88config.DTAG = check_and_set_d_tag_nip88(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"])
|
||||
nip88config.TIER_EVENT = check_and_set_tiereventid_nip88(identifier, "1")
|
||||
nip89config.NAME = name
|
||||
nip88config.IMAGE = nip89info["image"]
|
||||
nip88config.TITLE = name
|
||||
nip88config.AMOUNT_DAILY = 100
|
||||
nip88config.AMOUNT_MONTHLY = 2000
|
||||
nip88config.CONTENT = "Subscribe to the DVM for unlimited use during your subscription"
|
||||
nip88config.PERK1DESC = "Unlimited requests"
|
||||
nip88config.PERK2DESC = "Support NostrDVM & NostrSDK development"
|
||||
nip88config.PAYMENT_VERIFIER_PUBKEY = "5b5c045ecdf66fb540bdf2049fe0ef7f1a566fa427a4fe50d400a011b65a3a7e"
|
||||
|
||||
# admin_config.UPDATE_PROFILE = False
|
||||
# admin_config.REBROADCAST_NIP89 = False
|
||||
# admin_config.REBROADCAST_NIP88 = False
|
||||
|
||||
# admin_config.FETCH_NIP88 = True
|
||||
# admin_config.EVENTID = ""
|
||||
# admin_config.PRIVKEY = dvm_config.PRIVATE_KEY
|
||||
|
||||
return DicoverContentCurrentlyPopularGallery(name=name, dvm_config=dvm_config, nip89config=nip89config,
|
||||
nip88config=nip88config, options=options,
|
||||
admin_config=admin_config)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
process_venv(DicoverContentCurrentlyPopularGallery)
|
@ -9,12 +9,8 @@ class EventDefinitions:
|
||||
KIND_DM = Kind(4)
|
||||
KIND_REPOST = Kind(6)
|
||||
KIND_REACTION = Kind(7)
|
||||
KIND_ZAP = Kind(9735)
|
||||
KIND_RELAY_ANNOUNCEMENT = Kind(10002)
|
||||
KIND_ANNOUNCEMENT = Kind(31990)
|
||||
KIND_LONGFORM = Kind(30023)
|
||||
KIND_NIP94_METADATA = Kind(1063)
|
||||
KIND_FEEDBACK = Kind(7000)
|
||||
KIND_NIP93_GALLERYENTRY = Kind(1163)
|
||||
KIND_NIP90_EXTRACT_TEXT = Kind(5000)
|
||||
KIND_NIP90_RESULT_EXTRACT_TEXT = Kind(6000)
|
||||
KIND_NIP90_SUMMARIZE_TEXT = Kind(5001)
|
||||
@ -41,15 +37,21 @@ class EventDefinitions:
|
||||
KIND_NIP90_RESULTS_CONTENT_SEARCH = Kind(6302)
|
||||
KIND_NIP90_USER_SEARCH = Kind(5303)
|
||||
KIND_NIP90_RESULTS_USER_SEARCH = Kind(6303)
|
||||
KIND_NIP90_VISUAL_DISCOVERY = Kind(5304)
|
||||
KIND_NIP90_RESULT_VISUAL_DISCOVERY = Kind(6304)
|
||||
KIND_NIP90_DVM_SUBSCRIPTION = Kind(5906)
|
||||
KIND_NIP90_RESULT_DVM_SUBSCRIPTION = Kind(6906)
|
||||
|
||||
KIND_NIP90_GENERIC = Kind(5999)
|
||||
KIND_NIP90_RESULT_GENERIC = Kind(6999)
|
||||
|
||||
KIND_FEEDBACK = Kind(7000)
|
||||
KIND_NIP88_SUBSCRIBE_EVENT = Kind(7001)
|
||||
KIND_NIP88_STOP_SUBSCRIPTION_EVENT = Kind(7002)
|
||||
KIND_NIP88_PAYMENT_RECIPE = Kind(7003)
|
||||
KIND_ZAP = Kind(9735)
|
||||
KIND_RELAY_ANNOUNCEMENT = Kind(10002)
|
||||
KIND_ANNOUNCEMENT = Kind(31990)
|
||||
KIND_LONGFORM = Kind(30023)
|
||||
KIND_NIP88_TIER_EVENT = Kind(37001)
|
||||
|
||||
ANY_RESULT = [KIND_NIP90_RESULT_EXTRACT_TEXT,
|
||||
|
142
tests/discovery_gallery.py
Normal file
142
tests/discovery_gallery.py
Normal file
@ -0,0 +1,142 @@
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import dotenv
|
||||
from nostr_sdk import init_logger, LogLevel, Keys, NostrLibrary
|
||||
|
||||
from nostr_dvm.tasks.content_discovery_currently_popular_gallery import DicoverContentCurrentlyPopularGallery
|
||||
from nostr_dvm.tasks.people_discovery_wot import DiscoverPeopleWOT
|
||||
from nostr_dvm.utils.admin_utils import AdminConfig
|
||||
from nostr_dvm.utils.dvmconfig import build_default_config
|
||||
from nostr_dvm.utils.nip89_utils import create_amount_tag, NIP89Config, check_and_set_d_tag
|
||||
|
||||
rebroadcast_NIP89 = False # Announce NIP89 on startup
|
||||
rebroadcast_NIP65_Relay_List = True
|
||||
update_profile = True
|
||||
|
||||
global_update_rate = 1200 # set this high on first sync so db can fully sync before another process trys to.
|
||||
use_logger = True
|
||||
|
||||
RECONCILE_DB_RELAY_LIST = ["wss://relay.damus.io", "wss://nostr.mom"] # , "wss://relay.snort.social"]
|
||||
|
||||
if use_logger:
|
||||
init_logger(LogLevel.INFO)
|
||||
|
||||
|
||||
def build_example_gallery(name, identifier, admin_config, options, image, cost=0, update_rate=180, processing_msg=None,
|
||||
update_db=True):
|
||||
dvm_config = build_default_config(identifier)
|
||||
dvm_config.USE_OWN_VENV = False
|
||||
dvm_config.LOGLEVEL = LogLevel.INFO
|
||||
# dvm_config.SHOWLOG = True
|
||||
dvm_config.SCHEDULE_UPDATES_SECONDS = update_rate # Every 10 minutes
|
||||
dvm_config.UPDATE_DATABASE = update_db
|
||||
dvm_config.RECONCILE_DB_RELAY_LIST = RECONCILE_DB_RELAY_LIST
|
||||
dvm_config.LOGLEVEL = LogLevel.DEBUG
|
||||
dvm_config.FIX_COST = cost
|
||||
# dvm_config.RELAY_LIST = ["wss://dvms.f7z.io", "wss://nostr.oxtr.dev", "wss://relay.nostr.bg",
|
||||
# "wss://relay.nostr.net"]
|
||||
dvm_config.CUSTOM_PROCESSING_MESSAGE = processing_msg
|
||||
# dvm_config.RELAY_LIST = ["wss://dvms.f7z.io",
|
||||
# "wss://nostr.mom", "wss://nostr.oxtr.dev", "wss://relay.nostr.bg"
|
||||
# ]
|
||||
admin_config.LUD16 = dvm_config.LN_ADDRESS
|
||||
|
||||
# Add NIP89
|
||||
nip89info = {
|
||||
"name": name,
|
||||
"image": image,
|
||||
"picture": image,
|
||||
"about": "I show popular gallery entries",
|
||||
"lud16": dvm_config.LN_ADDRESS,
|
||||
"encryptionSupported": True,
|
||||
"cashuAccepted": True,
|
||||
"personalized": True,
|
||||
"amount": create_amount_tag(cost),
|
||||
"nip90Params": {
|
||||
"max_results": {
|
||||
"required": False,
|
||||
"values": [],
|
||||
"description": "The number of maximum results to return (default currently 200)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nip89config = NIP89Config()
|
||||
nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"])
|
||||
nip89config.CONTENT = json.dumps(nip89info)
|
||||
return DicoverContentCurrentlyPopularGallery(name=name, dvm_config=dvm_config, nip89config=nip89config,
|
||||
admin_config=admin_config, options=options)
|
||||
|
||||
|
||||
def playground():
|
||||
# Popular Global
|
||||
admin_config_global_wot = AdminConfig()
|
||||
admin_config_global_wot.REBROADCAST_NIP89 = rebroadcast_NIP89
|
||||
admin_config_global_wot.REBROADCAST_NIP65_RELAY_LIST = rebroadcast_NIP65_Relay_List
|
||||
admin_config_global_wot.UPDATE_PROFILE = update_profile
|
||||
# admin_config_global_popular.DELETE_NIP89 = True
|
||||
# admin_config_global_popular.PRIVKEY = ""
|
||||
# admin_config_global_popular.EVENTID = "2fea4ee2ccf0fa11db171113ffd7a676f800f34121478b7c9a4e73c2f1990028"
|
||||
# admin_config_global_popular.POW = True
|
||||
custom_processing_msg = ["Looking for people, that npubs in your Web of Trust follow, but you don't"]
|
||||
update_db = True
|
||||
|
||||
options_wot = {
|
||||
"db_name": "db/nostr_gallery.db",
|
||||
"generic_db_name": "db/nostr_recent_notes.db",
|
||||
"db_since": 60 * 60 * 24 * 30, # 1h since gmt,
|
||||
}
|
||||
|
||||
options_wot = {
|
||||
"db_name": "db/nostr_followlists.db",
|
||||
"db_since": 60 * 60 * 24 * 365, # 1h since gmt,
|
||||
}
|
||||
cost = 0
|
||||
image = "https://image.nostr.build/b29b6ec4bf9b6184f69d33cb44862db0d90a2dd9a506532e7ba5698af7d36210.jpg"
|
||||
discovery_wot = build_example_gallery("Gallery entries",
|
||||
"discovery_gallery_entries",
|
||||
admin_config=admin_config_global_wot,
|
||||
options=options_wot,
|
||||
image=image,
|
||||
cost=cost,
|
||||
update_rate=global_update_rate,
|
||||
processing_msg=custom_processing_msg,
|
||||
update_db=update_db)
|
||||
discovery_wot.run()
|
||||
|
||||
# discovery_test_sub = content_discovery_currently_popular.build_example_subscription("Currently Popular Notes DVM (with Subscriptions)", "discovery_content_test", admin_config)
|
||||
# discovery_test_sub.run()
|
||||
|
||||
# Subscription Manager DVM
|
||||
# subscription_config = DVMConfig()
|
||||
# subscription_config.PRIVATE_KEY = check_and_set_private_key("dvm_subscription")
|
||||
# npub = Keys.parse(subscription_config.PRIVATE_KEY).public_key().to_bech32()
|
||||
# invoice_key, admin_key, wallet_id, user_id, lnaddress = check_and_set_ln_bits_keys("dvm_subscription", npub)
|
||||
# subscription_config.LNBITS_INVOICE_KEY = invoice_key
|
||||
# subscription_config.LNBITS_ADMIN_KEY = admin_key # The dvm might pay failed jobs back
|
||||
# subscription_config.LNBITS_URL = os.getenv("LNBITS_HOST")
|
||||
# sub_admin_config = AdminConfig()
|
||||
# sub_admin_config.USERNPUBS = ["7782f93c5762538e1f7ccc5af83cd8018a528b9cd965048386ca1b75335f24c6"] #Add npubs of services that can contact the subscription handler
|
||||
|
||||
# currently there is none, but add this once subscriptions are live.
|
||||
# x = threading.Thread(target=Subscription, args=(Subscription(subscription_config, sub_admin_config),))
|
||||
# x.start()
|
||||
|
||||
# keep_alive()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
env_path = Path('.env')
|
||||
if not env_path.is_file():
|
||||
with open('.env', 'w') as f:
|
||||
print("Writing new .env file")
|
||||
f.write('')
|
||||
if env_path.is_file():
|
||||
print(f'loading environment from {env_path.resolve()}')
|
||||
dotenv.load_dotenv(env_path, verbose=True, override=True)
|
||||
else:
|
||||
raise FileNotFoundError(f'.env file not found at {env_path} ')
|
||||
playground()
|
@ -177,7 +177,7 @@ async def nostr_client_test_tts(prompt):
|
||||
return event.as_json()
|
||||
|
||||
|
||||
async def nostr_client_test_disovery(user, ptag):
|
||||
async def nostr_client_test_discovery(user, ptag):
|
||||
keys = Keys.parse(check_and_set_private_key("test_client"))
|
||||
|
||||
relay_list = ["wss://relay.damus.io", "wss://blastr.f7z.xyz",
|
||||
@ -205,7 +205,7 @@ async def nostr_client_test_disovery(user, ptag):
|
||||
return event.as_json()
|
||||
|
||||
|
||||
async def nostr_client_test_disovery_user(user, ptag):
|
||||
async def nostr_client_test_discovery_user(user, ptag):
|
||||
keys = Keys.parse(check_and_set_private_key("test_client"))
|
||||
|
||||
relay_list = ["wss://relay.damus.io", "wss://dvms.f7z.io",
|
||||
@ -231,6 +231,32 @@ async def nostr_client_test_disovery_user(user, ptag):
|
||||
print(eventid.to_hex())
|
||||
return event.as_json()
|
||||
|
||||
async def nostr_client_test_discovery_gallery(user, ptag):
|
||||
keys = Keys.parse(check_and_set_private_key("test_client"))
|
||||
|
||||
relay_list = ["wss://relay.damus.io", "wss://dvms.f7z.io",
|
||||
]
|
||||
|
||||
relaysTag = Tag.parse(relay_list)
|
||||
alttag = Tag.parse(["alt", "This is a NIP90 DVM AI task to find users"])
|
||||
paramTag = Tag.parse(["param", "user", user])
|
||||
pTag = Tag.parse(["p", ptag])
|
||||
|
||||
tags = [relaysTag, alttag, paramTag, pTag]
|
||||
|
||||
event = EventBuilder(EventDefinitions.KIND_NIP90_VISUAL_DISCOVERY, str("Give me visuals"),
|
||||
tags).to_event(keys)
|
||||
|
||||
signer = NostrSigner.keys(keys)
|
||||
client = Client(signer)
|
||||
for relay in relay_list:
|
||||
await client.add_relay(relay)
|
||||
await client.connect()
|
||||
config = DVMConfig
|
||||
eventid = await send_event(event, client=client, dvm_config=config)
|
||||
print(eventid.to_hex())
|
||||
return event.as_json()
|
||||
|
||||
|
||||
async def nostr_client_test_image_private(prompt, cashutoken):
|
||||
keys = Keys.parse(check_and_set_private_key("test_client"))
|
||||
@ -300,7 +326,9 @@ async def nostr_client():
|
||||
# await nostr_client_test_image("a beautiful purple ostrich watching the sunset")
|
||||
# await nostr_client_test_search_profile("dontbelieve")
|
||||
wot = ["99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64"]
|
||||
await nostr_client_test_disovery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "3553867e9376c1611367b5ad0488d7d0b6bfc3fca2010282cc0dc4666da4e7fb")
|
||||
#await nostr_client_test_discovery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "3553867e9376c1611367b5ad0488d7d0b6bfc3fca2010282cc0dc4666da4e7fb")
|
||||
await nostr_client_test_discovery_gallery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "4add3944eb596a27a650f9b954f5ed8dfefeec6ca50473605b0fbb058dd11306")
|
||||
|
||||
#await nostr_client_test_disovery_user("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64",
|
||||
# "58c52fdca7593dffea63ba6f758779d8251c6732f54e9dc0e56d7a1afe1bb1b6")
|
||||
|
||||
|
@ -115,19 +115,7 @@ async def test_gallery():
|
||||
Tag.parse(["alt", "Profile Gallery List"])
|
||||
]
|
||||
|
||||
keyhex = "27da5b78f4b1d1c33817f76cf4c40b733e99cd192585ea1b711142682c3594b9"
|
||||
keys = Keys.parse(keyhex)
|
||||
draft = {
|
||||
|
||||
"content": "Hello",
|
||||
"kind": 1,
|
||||
"pubkey": keys.public_key().to_hex(), # 48h since gmt,
|
||||
"tags": [],
|
||||
"createdAt": 16123123}
|
||||
|
||||
event = EventBuilder.text_note("Hello", []).custom_created_at(Timestamp.from_secs(1720464386)).to_event(keys)
|
||||
|
||||
print(event.as_json())
|
||||
# await gallery_announce_list(tags, dvm_config, client)
|
||||
|
||||
#evt = EventBuilder.delete([EventId.parse("40e7a72f10d9a6511dab897b3b4a94f7eff04f509886de95de3897d06ca9a92c")],
|
||||
|
Loading…
x
Reference in New Issue
Block a user