adding popular notes by topic dvms, add min number of reactions to existing content dvms

This commit is contained in:
Believethehype
2024-05-09 08:18:21 +02:00
parent 99a0f78982
commit 22413f627a
5 changed files with 363 additions and 17 deletions

View File

@@ -29,6 +29,7 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface):
last_schedule: int
db_since = 3600
db_name = "db/nostr_recent_notes.db"
min_reactions = 2
def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None,
admin_config: AdminConfig = None, options=None):
@@ -105,10 +106,10 @@ class DicoverContentCurrentlyPopular(DVMTaskInterface):
ns.finallist = {}
for event in events:
if event.created_at().as_secs() > timestamp_hour_ago:
ns.finallist[event.id().to_hex()] = 0
filt = Filter().kinds([definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REPOST, definitions.EventDefinitions.KIND_REACTION, definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(lasthour)
reactions = cli.database().query([filt])
ns.finallist[event.id().to_hex()] = len(reactions)
if len(reactions) >= self.min_reactions:
ns.finallist[event.id().to_hex()] = len(reactions)
result_list = []
finallist_sorted = sorted(ns.finallist.items(), key=lambda x: x[1], reverse=True)[:int(options["max_results"])]

View File

@@ -30,6 +30,7 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface):
last_schedule: int
db_since = 2 * 3600
db_name = "db/nostr_recent_notes2.db"
min_reactions = 2
def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None,
admin_config: AdminConfig = None, options=None):
@@ -141,12 +142,13 @@ class DicoverContentCurrentlyPopularFollowers(DVMTaskInterface):
ns.finallist = {}
for event in events:
if event.created_at().as_secs() > timestamp_hour_ago:
ns.finallist[event.id().to_hex()] = 0
filt = Filter().kinds(
[definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REACTION, definitions.EventDefinitions.KIND_REPOST,
definitions.EventDefinitions.KIND_NOTE]).event(event.id()).since(lasthour)
reactions = cli.database().query([filt])
ns.finallist[event.id().to_hex()] = len(reactions)
if len(reactions) >= self.min_reactions:
ns.finallist[event.id().to_hex()] = len(reactions)
finallist_sorted = sorted(ns.finallist.items(), key=lambda x: x[1], reverse=True)[:int(options["max_results"])]

View File

@@ -0,0 +1,293 @@
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
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
from nostr_dvm.utils.output_utils import post_process_list_to_events, post_process_list_to_users
"""
This File contains a Module to discover popular notes
Accepted Inputs: none
Outputs: A list of events
Params: None
"""
class DicoverContentCurrentlyPopularbyTopic(DVMTaskInterface):
KIND: Kind = EventDefinitions.KIND_NIP90_CONTENT_DISCOVERY
TASK: str = "discover-content"
FIX_COST: float = 0
dvm_config: DVMConfig
last_schedule: int
min_reactions = 2
db_since = 10*3600
db_name = "db/nostr_default_recent_notes.db"
search_list = []
avoid_list = []
def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, nip88config: NIP88Config = None,
admin_config: AdminConfig = None, options=None):
dvm_config.SCRIPT = os.path.abspath(__file__)
super().__init__(name=name, dvm_config=dvm_config, nip89config=nip89config, nip88config=nip88config,
admin_config=admin_config, options=options)
self.last_schedule = Timestamp.now().as_secs()
if self.options.get("search_list"):
self.search_list = self.options.get("search_list")
print(self.search_list)
if self.options.get("avoid_list"):
self.avoid_list = self.options.get("avoid_list")
if self.options.get("must_list"):
self.must_list = self.options.get("must_list")
if self.options.get("db_name"):
self.db_name = self.options.get("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)
self.sync_db()
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
def create_request_from_nostr_event(self, event, client=None, dvm_config=None):
self.dvm_config = dvm_config
print(self.dvm_config.PRIVATE_KEY)
request_form = {"jobID": event.id().to_hex()}
# default values
search = ""
max_results = 100
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
def process(self, request_form):
from nostr_sdk import Filter
from types import SimpleNamespace
ns = SimpleNamespace()
options = DVMTaskInterface.set_options(request_form)
opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)))
sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY)
keys = Keys.parse(sk.to_hex())
signer = NostrSigner.keys(keys)
database = NostrDatabase.sqlite(self.db_name)
cli = ClientBuilder().database(database).signer(signer).opts(opts).build()
cli.add_relay("wss://relay.damus.io")
cli.connect()
# Negentropy reconciliation
# Query events from database
filter1 = Filter().kind(definitions.EventDefinitions.KIND_NOTE)
events = cli.database().query([filter1])
print(len(events))
ns.finallist = {}
for event in events:
if all(ele in event.content().lower() for ele in self.must_list):
if any(ele in event.content().lower() for ele in self.search_list):
if not any(ele in event.content().lower() for ele in self.avoid_list):
filt = Filter().kinds(
[definitions.EventDefinitions.KIND_ZAP, definitions.EventDefinitions.KIND_REACTION,
definitions.EventDefinitions.KIND_REPOST,
definitions.EventDefinitions.KIND_NOTE]).event(event.id())
reactions = cli.database().query([filt])
if len(reactions) >= self.min_reactions:
ns.finallist[event.id().to_hex()] = len(reactions)
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())
print(len(result_list))
return json.dumps(result_list)
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_users(result)
# if not text/plain, don't post-process
return result
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:
self.sync_db()
self.last_schedule = Timestamp.now().as_secs()
return 1
def sync_db(self):
opts = (Options().wait_for_send(False).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)))
sk = SecretKey.from_hex(self.dvm_config.PRIVATE_KEY)
keys = Keys.parse(sk.to_hex())
signer = NostrSigner.keys(keys)
database = NostrDatabase.sqlite(self.db_name)
cli = ClientBuilder().signer(signer).database(database).opts(opts).build()
cli.add_relay("wss://relay.damus.io")
cli.connect()
timestamp_hour_ago = Timestamp.now().as_secs() - self.db_since
lasthour = Timestamp.from_secs(timestamp_hour_ago)
filter1 = Filter().kinds([definitions.EventDefinitions.KIND_NOTE, definitions.EventDefinitions.KIND_REACTION, definitions.EventDefinitions.KIND_ZAP]).since(lasthour) # Notes, reactions, zaps
# filter = Filter().author(keys.public_key())
print("Syncing notes of the last " + str(self.db_since) + " seconds.. this might take a while..")
dbopts = NegentropyOptions().direction(NegentropyDirection.DOWN)
cli.reconcile(filter1, dbopts)
database.delete(Filter().until(Timestamp.from_secs(
Timestamp.now().as_secs() - self.db_since))) # Clear old events so db doesn't get too full.
print("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, image, description):
dvm_config = build_default_config(identifier)
dvm_config.USE_OWN_VENV = False
dvm_config.SHOWLOG = True
dvm_config.SCHEDULE_UPDATES_SECONDS = 600 # Every 10 minutes
# Activate these to use a subscription based model instead
# dvm_config.SUBSCRIPTION_REQUIRED = True
# dvm_config.SUBSCRIPTION_DAILY_COST = 1
dvm_config.FIX_COST = 0
# Add NIP89
nip89info = {
"name": name,
"image": image,
"about": description,
"lud16": dvm_config.LN_ADDRESS,
"encryptionSupported": True,
"cashuAccepted": True,
"amount": "free",
"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 DicoverContentCurrentlyPopularbyTopic(name=name, dvm_config=dvm_config, nip89config=nip89config,
admin_config=admin_config, options=options)
def build_example_subscription(name, identifier, admin_config, options, image, description):
dvm_config = build_default_config(identifier)
dvm_config.USE_OWN_VENV = False
dvm_config.SHOWLOG = True
dvm_config.SCHEDULE_UPDATES_SECONDS = 600 # Every 10 minutes
# Activate these to use a subscription based model instead
# dvm_config.SUBSCRIPTION_DAILY_COST = 1
dvm_config.FIX_COST = 0
# Add NIP89
nip89info = {
"name": name,
"image": image,
"about": description,
"lud16": dvm_config.LN_ADDRESS,
"encryptionSupported": True,
"cashuAccepted": True,
"subscription": True,
"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 = "63a791cdc7bf78c14031616963105fce5793f532bb231687665b14fb6d805fdb"
# admin_config.PRIVKEY = dvm_config.PRIVATE_KEY
return DicoverContentCurrentlyPopularbyTopic(name=name, dvm_config=dvm_config, nip89config=nip89config,
nip88config=nip88config,
admin_config=admin_config,
options=options)
if __name__ == '__main__':
process_venv(DicoverContentCurrentlyPopularbyTopic)

View File

@@ -23,19 +23,69 @@ def playground():
admin_config = AdminConfig()
admin_config.REBROADCAST_NIP89 = False
admin_config.UPDATE_PROFILE = False
#admin_config.DELETE_NIP89 = True
#admin_config.PRIVKEY = ""
#admin_config.EVENTID = ""
# admin_config.DELETE_NIP89 = True
# admin_config.PRIVKEY = ""
# admin_config.EVENTID = ""
#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()
# 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()
discovery_test_sub = content_discovery_currently_popular_topic.build_example("Garden & Growth", "discovery_content_garden", admin_config)
options_plants = {
"search_list": ["garden", "gardening", "nature", " plants ", " plant ", " herb ", " herbs " " pine ",
"homesteading", "rosemary", "chicken", "🪻", "🌿", "☘️", "🌲", "flower", "forest", "watering",
"permies", "planting", "farm", "vegetable", "fruit", " grass ", "sunshine",
"#flowerstr", "#bloomscrolling", "#treestr", "#plantstr"],
"avoid_list": ["porn", "smoke", "nsfw", "bitcoin", "bolt12", "bolt11", "github", "currency", "utxo",
"encryption", "government", "airpod", "ipad", "iphone", "android", "warren",
"moderna", "pfizer",
"murder", "tax", "engagement", "hodlers", "hodl", "gdp", "global markets", "crypto", "wherostr",
"presidency", "dollar", "asset", "microsoft", "amazon", "billionaire", "ceo", "industry",
"white house", "blocks", "streaming", "summary", "wealth", "beef", "cunt", "nigger", "business",
"retail", "bakery", "synth", "slaughterhouse", "hamas", "dog days", "ww3", "socialmedia",
"nintendo", "signature", "deepfake", "congressman", "cypherpunk", "minister", "dissentwatch",
"inkblot", "covid", "robot", "pandemic", "bethesda", "zap farming", " defi ", " minister ",
"nostr-hotter-site", " ai ", "palestine", "https://boards.4chan", "https://techcrunch.com", "https://screenrant.com"],
"db_name": "db/nostr_recent_notes_plants.db",
"db_since": 10 * 60 * 60} # 10h
image = "https://image.nostr.build/a816f3f5e98e91e8a47d50f4cd7a2c17545f556d9bb0a6086a659b9abdf7ab68.jpg"
description = "I show recent notes about plants and gardening"
discovery_test_sub = content_discovery_currently_popular_topic.build_example("Garden & Growth",
"discovery_content_garden",
admin_config, options_plants, image,
description)
discovery_test_sub.run()
#discovery_test = content_discovery_currently_popular.build_example("Currently Popular Notes DVM",
options_animal = {
"search_list": ["catstr", "pawstr", "dogstr", " cat ", " cats ", "🐾", "🐈", "🐕" , " dog ", " dogs ", " fluffy ", "animal",
" duck", " lion ", " lions ", " fox ", " foxes ", " koala ", " koalas ", "capybara", "squirrel", "monkey", "panda", "alpaca", " otter"],
"avoid_list": ["porn", "smoke", "nsfw", "bitcoin", "bolt12", "bolt11", "github", "currency", "utxo",
"encryption", "government", "airpod", "ipad", "iphone", "android", "warren",
"moderna", "pfizer",
"murder", "tax", "engagement", "hodlers", "hodl", "gdp", "global markets", "crypto", "wherostr",
"presidency", "dollar", "asset", "microsoft", "amazon", "billionaire", "ceo", "industry",
"white house", "blocks", "streaming", "summary", "wealth", "beef", "cunt", "nigger", "business",
"retail", "bakery", "synth", "slaughterhouse", "hamas", "dog days", "ww3", "socialmedia",
"nintendo", "signature", "deepfake", "congressman", "fried chicken", "cypherpunk",
"chef", "cooked", "foodstr", "minister", "dissentwatch", "inkblot", "covid", "robot", "pandemic",
" dies ", "bethesda", " defi ", " minister ", "nostr-hotter-site", " ai ", "palestine", " hit by a", "https://boards.4chan", "https://techcrunch.com", "https://screenrant.com"],
"must_list": ["http"],
"db_name": "db/nostr_recent_notes_animals.db",
"db_since": 48 * 60 * 60} # 10h
image = "https://image.nostr.build/f609311532c470f663e129510a76c9a1912ae9bc4aaaf058e5ba21cfb512c88e.jpg"
description = "I show recent notes about animals"
discovery_test_sub2 = content_discovery_currently_popular_topic.build_example("Fluffy Frens",
"discovery_content_fluffy",
admin_config, options_animal, image,
description)
discovery_test_sub2.run()
# discovery_test = content_discovery_currently_popular.build_example("Currently Popular Notes DVM",
# "discovery_content_test", admin_config)
#discovery_test.run()
# discovery_test.run()
subscription_config = DVMConfig()
subscription_config.PRIVATE_KEY = check_and_set_private_key("dvm_subscription")
@@ -45,11 +95,11 @@ def playground():
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
#x = threading.Thread(target=Subscription, args=(Subscription(subscription_config, sub_admin_config),))
#x.start()
# sub_admin_config.USERNPUBS = ["7782f93c5762538e1f7ccc5af83cd8018a528b9cd965048386ca1b75335f24c6"] #Add npubs of services that can contact the subscription handler
# x = threading.Thread(target=Subscription, args=(Subscription(subscription_config, sub_admin_config),))
# x.start()
#keep_alive()
# keep_alive()
if __name__ == '__main__':

View File

@@ -273,7 +273,7 @@ def nostr_client():
# nostr_client_test_image("a beautiful purple ostrich watching the sunset")
# nostr_client_test_search_profile("dontbelieve")
wot = ["99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64"]
nostr_client_test_disovery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "a21592a70ef9a00695efb3f7e816e17742d251559aff154b16d063a408bcd74d")
nostr_client_test_disovery("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64", "7b7373dd58554ff4c0d28b401b9eae114bd92e30d872ae843b9a217375d66f9d")
#nostr_client_test_censor_filter(wot)
#nostr_client_test_inactive_filter("99bb5591c9116600f845107d31f9b59e2f7c7e09a1ff802e84f1d43da557ca64")