From 4e782de528f6036c58e8f4d213ee6dccad728ff0 Mon Sep 17 00:00:00 2001 From: codey Date: Sun, 17 Nov 2024 13:41:20 -0500 Subject: [PATCH] stoof --- cah/__init__.py | 1 + cah/__main__.py | 3 + endpoints/ai.py | 18 ++++- endpoints/karma.py | 15 ++-- tmp/Lyrics/plugin.py | 170 +++++++++++++++++++++++++++++++++++++++++++ tmp/README.md | 1 + 6 files changed, 198 insertions(+), 10 deletions(-) create mode 100644 cah/__init__.py create mode 100644 cah/__main__.py create mode 100644 tmp/Lyrics/plugin.py create mode 100644 tmp/README.md diff --git a/cah/__init__.py b/cah/__init__.py new file mode 100644 index 0000000..e45d2b3 --- /dev/null +++ b/cah/__init__.py @@ -0,0 +1 @@ +#!/usr/bin/env python3.12 \ No newline at end of file diff --git a/cah/__main__.py b/cah/__main__.py new file mode 100644 index 0000000..ad8ed69 --- /dev/null +++ b/cah/__main__.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python3.12 + +import constructors \ No newline at end of file diff --git a/endpoints/ai.py b/endpoints/ai.py index 0b1fb72..64fd8ac 100644 --- a/endpoints/ai.py +++ b/endpoints/ai.py @@ -169,13 +169,23 @@ class AI(FastAPI): # } # ai_req_data = { # 'max_context_length': 8192, - # 'max_length': 256, - # 'temperature': 0.3, + # 'max_length': 512, + # 'temperature': 0, + # 'n': 1, + # 'top_k': 30, + # 'top_a': 0, + # 'top_p': 0, + # 'typical': 0, + # 'mirostat': 0, + # 'use_default_badwordsids': False, + # 'rep_pen': 1.0, + # 'rep_pen_range': 320, + # 'rep_pen_slope': 0.05, # 'quiet': 1, # 'bypass_eos': False, - # 'trim_stop': True, + # # 'trim_stop': True, # 'sampler_order': [6,0,1,3,4,2,5], - # 'memory': "You are a helpful assistant who will provide only totally accurate tidbits of info on songs the user may listen to. You do not include information about which album a song was released on, or when it was released, and do not mention that you are not including this information in your response. If the input provided is not a song you are aware of, simply state that. Begin your output at your own response.", + # 'memory': "You are a helpful assistant who will provide ONLY TOTALLY ACCURATE tidbits of info on songs the user may listen to. You do not include information about which album a song was released on, or when it was released, and do not mention that you are not including this information in your response. If the input provided is not a song you are aware of, simply state that. Begin your output at your own response.", # 'stop': ['### Inst', '### Resp'], # 'prompt': ai_question # } diff --git a/endpoints/karma.py b/endpoints/karma.py index a94feca..a71c653 100644 --- a/endpoints/karma.py +++ b/endpoints/karma.py @@ -41,7 +41,7 @@ class KarmaDB: async def get_karma(self, keyword: str) -> int | dict: async with sqlite3.connect(self.db_path, timeout=2) as db_conn: - async with db_conn.execute("SELECT score FROM karma WHERE keyword = ? LIMIT 1", (keyword,)) as db_cursor: + async with db_conn.execute("SELECT score FROM karma WHERE keyword LIKE ? LIMIT 1", (keyword,)) as db_cursor: try: (score,) = await db_cursor.fetchone() return score @@ -65,7 +65,7 @@ class KarmaDB: return modifier = "score + 1" if not flag else "score - 1" - query = f"UPDATE karma SET score = {modifier}, last_change = ? WHERE keyword = ?" + query = f"UPDATE karma SET score = {modifier}, last_change = ? WHERE keyword LIKE ?" new_keyword_query = "INSERT INTO karma(keyword, score, last_change) VALUES(?, ?, ?)" friendly_flag = "++" if not flag else "--" audit_message = f"{granter} adjusted karma for {keyword} @ {datetime.datetime.now().isoformat()}: {friendly_flag}" @@ -119,7 +119,7 @@ class Karma(FastAPI): """ /karma/top/ Get top keywords for karma - Requires key + (Requires key) """ if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')): @@ -140,13 +140,16 @@ class Karma(FastAPI): 'errorText': 'Exception occurred.', } - async def get_karma_handler(self, data: ValidKarmaRetrievalRequest): + async def get_karma_handler(self, data: ValidKarmaRetrievalRequest, request: Request): """ /karma/get/ Get current karma value - Requires key + (Requires key) """ + if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')): + raise HTTPException(status_code=403, detail="Unauthorized") + keyword = data.keyword try: count = await self.db.get_karma(keyword) @@ -165,7 +168,7 @@ class Karma(FastAPI): """ /karma/update/ Update karma count - Requires key + (Requires key) """ if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With'), 2): diff --git a/tmp/Lyrics/plugin.py b/tmp/Lyrics/plugin.py new file mode 100644 index 0000000..3ef7810 --- /dev/null +++ b/tmp/Lyrics/plugin.py @@ -0,0 +1,170 @@ +### +# Copyright (c) 2024, codey +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions, and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions, and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the author of this software nor the name of +# contributors to this software may be used to endorse or promote products +# derived from this software without specific prior written consent. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +### + +import textwrap +import time +import re +import requests + +from supybot import utils, plugins, ircutils, callbacks, conf, ircdb +from supybot.commands import * +from supybot.i18n import PluginInternationalization +from supybot.i18n import internationalizeDocstring + + +_ = PluginInternationalization('Lyrics') + + +class SearchException(Exception): + pass + +class Lyrics(callbacks.Plugin): + """Song Lyrics Search""" + threaded = True + + + + @wrap(['text']) + def sing(self, irc, msg, args, query): + """ + + Sing : + """ + + """Check if Lyrics Search is enabled in this context/channel""" + if not(self.registryValue('enable', network=irc.network, channel=msg.channel)): + return irc.noReply() + + """Check for botwide ignores""" + if ircdb.checkIgnored(msg.prefix, msg.args[0]): + return irc.noReply() + + use_mores = self.registryValue('mores', network=irc.network, channel=msg.channel) + truncate = self.registryValue('truncate', network=irc.network, channel=msg.channel) + lines_to_send = self.registryValue('lines', network=irc.network, channel=msg.channel) + quiet = self.registryValue('quiet', network=irc.network, channel=msg.channel) + verbose = self.registryValue('verbose', network=irc.network, channel=msg.channel) + can_flood = self.registryValue('floodexempt') + + + subsearch = None + trailer = " [...]" + query = "".join(query.strip()) + colons = len(re.findall(r':', query)) + dashes = len(re.findall(r'\s-\s', query)) + has_subsearch = (colons > 1) + + + """Check for valid query ( must contain : or - )""" + if not(colons) and not(dashes): + irc.reply("\002\00304Invalid query! " \ + "Query format should be either : , - , or optionally " \ + " : : ", prefixNick=False) + return + + + if colons: + artist = query.split(":")[0].strip() + song = query.split(":")[1].strip() + else: + artist = query.split(" - ", maxsplit=1)[0].strip() + song = query.split(" - ", maxsplit=1)[1].strip() + + searchObj = { + 'a': artist, + 's': song, + 'src': 'IRC-SHARED', + 'extras': True + } + + headers = { + 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0', + 'Content-Type': 'application/json; charset=utf-8' + } + + if has_subsearch: + subsearch = query.split(":")[2].strip() + searchObj['sub'] = subsearch + + try: + if not(quiet): + irc.reply("\002\00307Searching...", + private=not(verbose), notice=not(verbose), prefixNick=False) + + request = requests.post(self.registryValue('host'), + json=searchObj, + timeout=(10, 20), verify=False, headers=headers) + + request.raise_for_status() + + response = request.json() + if response.get('err'): + raise SearchException(response.get('errorText')) + + returned_artist = response.get('artist') + returned_song = response.get('song') + + if not(quiet): + irc.reply("\002\00309Found: %s - %s" + % (returned_artist, returned_song), + notice=not(verbose), private=not(verbose), + prefixNick=False) + + lyrics = response.get('lyrics') + lyrics = re.sub(r'
', ' / ', lyrics) + + if truncate and use_mores: + irc.reply(lyrics, prefixNick=False) + return + + wrapped_lyrics = textwrap.wrap(text=lyrics, + width=360, + break_on_hyphens=True, + break_long_words=True) + + if not(truncate): + lines_to_send = len(wrapped_lyrics) + + for idx, line in enumerate(wrapped_lyrics): + line = re.sub(r'/(\s{0,})$', '', line).strip() + if idx >= lines_to_send: + break + truncated = (idx+1 == lines_to_send and truncate) + irc.reply(line.strip() + (trailer if truncated else ''), prefixNick=False) + + if idx >= 5 and not(can_flood): + time.sleep(0.5) # Avoid RecvQ by sleeping for 0.5s starting with the 5th line of output + + return + except Exception as e: + irc.reply(f"\002\00304Error: {str(e)}", prefixNick=False) + return + +Class = Lyrics \ No newline at end of file diff --git a/tmp/README.md b/tmp/README.md new file mode 100644 index 0000000..ab1fbdd --- /dev/null +++ b/tmp/README.md @@ -0,0 +1 @@ +# This stuff does not belong here and will be removed \ No newline at end of file