This commit is contained in:
Nathan Rashleigh committed 2024-04-08 10:46:14 +10:00
1 parent d82a7fdf1e
commit 335eb8c4ac
16 files changed
+370 -5930

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
# A generic, single database configuration.
[dotenv]
dotenv_path = .env
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
-3913
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
from db.base import Base
from db.attachment import Attachment
from db.meme import Meme
+15
View File
@@ -0,0 +1,15 @@
from sqlalchemy import create_engine, Column, Integer, String, JSON, Uuid
from db.base import Base
# Define a model with a JSON column
class Attachment(Base):
__tablename__ = 'attachments'
id = Column(Uuid, primary_key=True)
msg_id = Column(Integer, nullable=False, index=True)
attributes = Column(JSON, nullable=False)
vision = Column(JSON, nullable=False)
message = Column(JSON, nullable=False)
guild = Column(JSON, nullable=False)
channel = Column(JSON, nullable=False)
+3
View File
@@ -0,0 +1,3 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
+12
View File
@@ -0,0 +1,12 @@
from sqlalchemy import Column, Integer, String, JSON, Uuid
from db.base import Base
# Define a model with a JSON column
class Meme(Base):
__tablename__ = 'memes'
id = Column(Uuid, primary_key=True)
url = Column(String, nullable=False)
text = Column(String, nullable=False)
tags = Column(JSON, nullable=False)
+16
View File
@@ -0,0 +1,16 @@
from sqlalchemy import create_engine, Column, Integer, String, Engine
from alembic.config import Config
from alembic import command
from dotenv import dotenv_values
# Function to perform the database migration
def migrate_db(engine: Engine, db_url):
# Configure Alembic
alembic_cfg = Config()
alembic_cfg.set_main_option("script_location", "migrations")
alembic_cfg.set_main_option("sqlalchemy.url", db_url)
# Run migrations using Alembic
command.upgrade(alembic_cfg, "head")
print('db up to date')
-1897
View File
File diff suppressed because it is too large. Load diff
-26
View File
@@ -1,26 +0,0 @@
from google.cloud import vision
from google.cloud.vision_v1 import types
from dotenv import load_dotenv
load_dotenv()
crows = 'https://cdn.discordapp.com/attachments/367936426962190336/1222335573855834214/AjPuqci.png?ex=6615d7b6&is=660362b6&hm=e364398ce7401334298eb82bddedab56d944f5833508fde4b07363b329a95c6f&'
# Authenticate the client
client = vision.ImageAnnotatorClient()
# Perform text detection
features = [types.Feature(type=types.Feature.Type.TEXT_DETECTION)]
request = {
'image': {
'source': { 'image_uri': crows }
},
'features': features
}
response: types.AnnotateImageResponse = client.annotate_image(request=request)
texts = response.text_annotations[0].description
print(texts)
+36 -61
View File
@@ -19,11 +19,11 @@ from dotenv import dotenv_values, load_dotenv
from google.cloud import vision as google_vision from google.cloud import vision as google_vision
from google.protobuf.json_format import MessageToDict, MessageToJson from google.protobuf.json_format import MessageToDict, MessageToJson
from google.cloud.vision_v1 import types from google.cloud.vision_v1 import types
from minio import Minio
import meilisearch import meilisearch
from urllib3.util import Url, url from urllib3.util import Url, url
import uploader from sqlalchemy import create_engine
from db.migrate import migrate_db
# need to change the env for the google api calls # need to change the env for the google api calls
load_dotenv() load_dotenv()
@@ -55,42 +55,16 @@ class MemeDocument:
text: str text: str
tags: List[str] tags: List[str]
@dataclass def detect_text(url, vision):
class DiscordAttachmentMessage: request = {
id: UUID 'image': { 'source': { 'image_uri': url } },
msg_id: int 'features': [types.Feature(type=types.Feature.Type.TEXT_DETECTION)],
url: str }
upload_url: str
guild_name: str
channel_name: str
vision_json: str | None
message_json: Dict[str, Any]
guild_json: Dict[str, Any]
channel_json: Dict[str, Any]
def document_dir(self): response: types.AnnotateImageResponse = vision.annotate_image(request=request)
return f'{DATA_DIR}/guilds/{self.guild_name}/{self.channel_name}' vision_json = json.loads(types.AnnotateImageResponse.to_json(response))
def file_dir(self): return request
return f"{DATA_DIR}/imgs/"
def detect_text(self, vision):
request = {
'image': { 'source': { 'image_uri': self.url } },
'features': [types.Feature(type=types.Feature.Type.TEXT_DETECTION)],
}
response: types.AnnotateImageResponse = vision.annotate_image(request=request)
self.vision_json = json.loads(types.AnnotateImageResponse.to_json(response))
if len(response.text_annotations) > 0:
self.text = response.text_annotations[0].description
return request
def persist(self):
with open(f'{self.document_dir()}/{self.id}.json', 'w') as f:
json.dump(vars(self), f, indent=4)
def filter_message_img_urls(messages): def filter_message_img_urls(messages):
url_lists = map( url_lists = map(
@@ -203,38 +177,39 @@ async def check_bucket_exists(storage, bucket_name):
raise # Reraise other exceptions raise # Reraise other exceptions
async def main(): async def main():
assert config['MINIO_URL'] assert config['STORAGE_URL']
assert config['POSTGRES_URL']
vision = google_vision.ImageAnnotatorClient() vision = google_vision.ImageAnnotatorClient()
# storage = Minio(config['MINIO_URL'], # db setup
# access_key=config['MINIO_ACCESS_KEY'], db_url = config['POSTGRES_URL']
# secret_key=config['MINIO_SECRET_KEY'], db_engine = create_engine(db_url)
# ) migrate_db(db_engine, db_url)
aioboto = aiobotocore_get_session() # aioboto = aiobotocore_get_session()
async with aioboto.create_client( # async with aioboto.create_client(
's3', # 's3',
endpoint_url=config['STORAGE_URL'], # endpoint_url=config['STORAGE_URL'],
aws_access_key_id=config['STORAGE_ACCESS_KEY'], # aws_access_key_id=config['STORAGE_ACCESS_KEY'],
aws_secret_access_key=config['STORAGE_SECRET_KEY'], # aws_secret_access_key=config['STORAGE_SECRET_KEY'],
) as storage: # ) as storage:
storage: S3Client # storage: S3Client
storage_bucket = config['UPLOAD_BUCKET'] # storage_bucket = config['UPLOAD_BUCKET']
assert storage_bucket # assert storage_bucket
# Make the bucket if it doesn't exist. # # Make the bucket if it doesn't exist.
exists = await check_bucket_exists(storage, storage_bucket) # exists = await check_bucket_exists(storage, storage_bucket)
if not exists: # if not exists:
await storage.create_bucket(Bucket=storage_bucket) # await storage.create_bucket(Bucket=storage_bucket)
print("Created bucket", storage_bucket) # print("Created bucket", storage_bucket)
else: # else:
print("Bucket", storage_bucket, "already exists") # print("Bucket", storage_bucket, "already exists")
async with aiohttp.ClientSession() as session: # async with aiohttp.ClientSession() as session:
channels = [download_channel_attachments(session, storage, vision, channel_id) for channel_id in CHANNEL_IDS] # channels = [download_channel_attachments(session, storage, vision, channel_id) for channel_id in CHANNEL_IDS]
memes = await asyncio.gather(*channels) # memes = await asyncio.gather(*channels)
asyncio.run(main()) asyncio.run(main())
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+86
View File
@@ -0,0 +1,86 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from dotenv import dotenv_values
from db import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
env = dotenv_values(".env")
assert env['POSTGRES_URL']
config.set_main_option('sqlalchemy.url', env['POSTGRES_URL'])
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+26
View File
@@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1,49 @@
"""Create Memes and Attachments table
Revision ID: e04bee35feab
Revises:
Create Date: 2024-04-08 10:45:47.138438
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'e04bee35feab'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('attachments',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('msg_id', sa.Integer(), nullable=False),
sa.Column('attributes', sa.JSON(), nullable=False),
sa.Column('vision', sa.JSON(), nullable=False),
sa.Column('message', sa.JSON(), nullable=False),
sa.Column('guild', sa.JSON(), nullable=False),
sa.Column('channel', sa.JSON(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_attachments_msg_id'), 'attachments', ['msg_id'], unique=False)
op.create_table('memes',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('url', sa.String(), nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('tags', sa.JSON(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('memes')
op.drop_index(op.f('ix_attachments_msg_id'), table_name='attachments')
op.drop_table('attachments')
# ### end Alembic commands ###
+4 -2
View File
@@ -3,5 +3,7 @@ aiohttp
google-cloud-vision google-cloud-vision
meilisearch meilisearch
pillow pillow
minio aiobotocore
aiobotocore sqlalchemy
alembic
psycopg2-binary
-31
View File
@@ -1,31 +0,0 @@
from minio import Minio
def upload(config, document, source_file):
assert config['MINIO_URL']
client = Minio(config['MINIO_URL'],
access_key=config['MINIO_ACCESS_KEY'],
secret_key=config['MINIO_SECRET_KEY'],
)
# The destination bucket and filename on the MinIO server
bucket_name = config['UPLOAD_BUCKET']
destination_file = document.url
# Make the bucket if it doesn't exist.
found = client.bucket_exists(bucket_name)
if not found:
client.make_bucket(bucket_name)
print("Created bucket", bucket_name)
else:
print("Bucket", bucket_name, "already exists")
# Upload the file, renaming it in the process
client.fput_object(
bucket_name, destination_file, source_file,
)
print(
source_file, "successfully uploaded as object",
destination_file, "to bucket", bucket_name,
)