Init Alas
This commit is contained in:
commit
c810c34b97
50 changed files with 11740 additions and 0 deletions
411
.gitignore
vendored
Normal file
411
.gitignore
vendored
Normal file
|
@ -0,0 +1,411 @@
|
|||
# Created by https://www.toptal.com/developers/gitignore/api/linux,windows,macos,emacs,python,nextjs,intellij+all,visualstudiocode
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=linux,windows,macos,emacs,python,nextjs,intellij+all,visualstudiocode
|
||||
|
||||
### Emacs ###
|
||||
# -*- mode: gitignore; -*-
|
||||
*~
|
||||
\#*\#
|
||||
/.emacs.desktop
|
||||
/.emacs.desktop.lock
|
||||
*.elc
|
||||
auto-save-list
|
||||
tramp
|
||||
.\#*
|
||||
|
||||
# Org-mode
|
||||
.org-id-locations
|
||||
*_archive
|
||||
|
||||
# flymake-mode
|
||||
*_flymake.*
|
||||
|
||||
# eshell files
|
||||
/eshell/history
|
||||
/eshell/lastdir
|
||||
|
||||
# elpa packages
|
||||
/elpa/
|
||||
|
||||
# reftex files
|
||||
*.rel
|
||||
|
||||
# AUCTeX auto folder
|
||||
/auto/
|
||||
|
||||
# cask packages
|
||||
.cask/
|
||||
dist/
|
||||
|
||||
# Flycheck
|
||||
flycheck_*.el
|
||||
|
||||
# server auth directory
|
||||
/server/
|
||||
|
||||
# projectiles files
|
||||
.projectile
|
||||
|
||||
# directory configuration
|
||||
.dir-locals.el
|
||||
|
||||
# network security
|
||||
/network-security.data
|
||||
|
||||
|
||||
### Intellij+all ###
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### Intellij+all Patch ###
|
||||
# Ignore everything but code style settings and run configurations
|
||||
# that are supposed to be shared within teams.
|
||||
|
||||
.idea/*
|
||||
|
||||
!.idea/codeStyles
|
||||
!.idea/runConfigurations
|
||||
|
||||
### Linux ###
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### macOS Patch ###
|
||||
# iCloud generated files
|
||||
*.icloud
|
||||
|
||||
### NextJS ###
|
||||
# Next build dir
|
||||
.next/
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
### VisualStudioCode ###
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
### VisualStudioCode Patch ###
|
||||
# Ignore all local history of files
|
||||
.history
|
||||
.ionide
|
||||
|
||||
# Support for Project snippet scope
|
||||
.vscode/*.code-snippets
|
||||
|
||||
# Ignore code-workspaces
|
||||
*.code-workspace
|
||||
|
||||
### Windows ###
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
Thumbs.db:encryptable
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/linux,windows,macos,emacs,python,nextjs,intellij+all,visualstudiocode
|
||||
|
||||
.idea/
|
||||
api/alas/cardiffnlp/
|
||||
api/alas/microsoft/
|
||||
api/alas/wandb
|
0
api/README.md
Normal file
0
api/README.md
Normal file
0
api/alas/__init__.py
Normal file
0
api/alas/__init__.py
Normal file
0
api/alas/evaluators/__init__.py
Normal file
0
api/alas/evaluators/__init__.py
Normal file
0
api/alas/evaluators/dalle/__init__.py
Normal file
0
api/alas/evaluators/dalle/__init__.py
Normal file
24
api/alas/evaluators/dalle/consts.py
Normal file
24
api/alas/evaluators/dalle/consts.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
from enum import Enum
|
||||
|
||||
DEFAULT_IMG_OUTPUT_DIR = 'generations'
|
||||
|
||||
DALLE_MODEL_MINI = "dalle-mini/dalle-mini/mini-1:v0" # the original DALL-E Mini. Fastest yet suboptimal results
|
||||
DALLE_MODEL_MEGA = "dalle-mini/dalle-mini/mega-1-fp16:latest" # the advanced version of DALL-E Mini. Requires more compute and VRAM
|
||||
DALLE_MODEL_MEGA_FULL = "dalle-mini/dalle-mini/mega-1:latest" # DALL-E Mega. Warning: requires significantly more storage and GPU RAM
|
||||
DALLE_COMMIT_ID = None
|
||||
|
||||
# VQGAN model
|
||||
VQGAN_REPO = "dalle-mini/vqgan_imagenet_f16_16384"
|
||||
VQGAN_COMMIT_ID = "e93a26e7707683d349bf5d5c41c5b0ef69b677a9"
|
||||
|
||||
|
||||
# We can customize generation parameters (see https://huggingface.co/blog/how-to-generate)
|
||||
GEN_TOP_K = None
|
||||
GEN_TOP_P = None
|
||||
TEMPERATURE = None
|
||||
COND_SCALE = 10.0
|
||||
|
||||
class ModelSize(Enum):
|
||||
MINI = "Mini"
|
||||
MEGA = "Mega"
|
||||
MEGA_FULL = "Mega_full"
|
115
api/alas/evaluators/dalle/dalle.py
Normal file
115
api/alas/evaluators/dalle/dalle.py
Normal file
|
@ -0,0 +1,115 @@
|
|||
import os
|
||||
import random
|
||||
from functools import partial
|
||||
|
||||
import jax
|
||||
import numpy as np
|
||||
import jax.numpy as jnp
|
||||
from PIL import Image
|
||||
|
||||
from dalle_mini import DalleBart, DalleBartProcessor
|
||||
from vqgan_jax.modeling_flax_vqgan import VQModel
|
||||
|
||||
from flax.jax_utils import replicate
|
||||
from flax.training.common_utils import shard_prng_key
|
||||
|
||||
import wandb
|
||||
|
||||
from .consts import COND_SCALE, DALLE_COMMIT_ID, DALLE_MODEL_MEGA_FULL, DALLE_MODEL_MEGA, DALLE_MODEL_MINI, GEN_TOP_K, \
|
||||
GEN_TOP_P, TEMPERATURE, VQGAN_COMMIT_ID, VQGAN_REPO, ModelSize
|
||||
|
||||
os.environ[
|
||||
"XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform" # https://github.com/saharmor/dalle-playground/issues/14#issuecomment-1147849318
|
||||
os.environ["WANDB_SILENT"] = "true"
|
||||
wandb.init(anonymous="must")
|
||||
|
||||
|
||||
# model inference
|
||||
@partial(jax.pmap, axis_name="batch", static_broadcasted_argnums=(3, 4, 5, 6, 7))
|
||||
def p_generate(
|
||||
tokenized_prompt, key, params, top_k, top_p, temperature, condition_scale, model
|
||||
):
|
||||
return model.generate(
|
||||
**tokenized_prompt,
|
||||
prng_key=key,
|
||||
params=params,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
temperature=temperature,
|
||||
condition_scale=condition_scale,
|
||||
)
|
||||
|
||||
|
||||
# decode images
|
||||
@partial(jax.pmap, axis_name="batch", static_broadcasted_argnums=(0))
|
||||
def p_decode(vqgan, indices, params):
|
||||
return vqgan.decode_code(indices, params=params)
|
||||
|
||||
|
||||
class DalleModel:
|
||||
def __init__(self, model_version: ModelSize) -> None:
|
||||
if model_version == ModelSize.MEGA_FULL:
|
||||
dalle_model = DALLE_MODEL_MEGA_FULL
|
||||
dtype = jnp.float16
|
||||
elif model_version == ModelSize.MEGA:
|
||||
dalle_model = DALLE_MODEL_MEGA
|
||||
dtype = jnp.float16
|
||||
else:
|
||||
dalle_model = DALLE_MODEL_MINI
|
||||
dtype = jnp.float32
|
||||
|
||||
# Load dalle-mini
|
||||
self.model, params = DalleBart.from_pretrained(
|
||||
dalle_model, revision=DALLE_COMMIT_ID, dtype=dtype, _do_init=False
|
||||
)
|
||||
|
||||
# Load VQGAN
|
||||
self.vqgan, vqgan_params = VQModel.from_pretrained(
|
||||
VQGAN_REPO, revision=VQGAN_COMMIT_ID, _do_init=False
|
||||
)
|
||||
|
||||
self.params = replicate(params)
|
||||
self.vqgan_params = replicate(vqgan_params)
|
||||
|
||||
self.processor = DalleBartProcessor.from_pretrained(dalle_model, revision=DALLE_COMMIT_ID)
|
||||
|
||||
def tokenize_prompt(self, prompt: str):
|
||||
tokenized_prompt = self.processor([prompt])
|
||||
return replicate(tokenized_prompt)
|
||||
|
||||
def eval(self, prompt: str, num_predictions: int):
|
||||
tokenized_prompt = self.tokenize_prompt(prompt)
|
||||
|
||||
# create a random key
|
||||
seed = random.randint(0, 2 ** 32 - 1)
|
||||
key = jax.random.PRNGKey(seed)
|
||||
|
||||
# generate images
|
||||
images = []
|
||||
for i in range(max(num_predictions // jax.device_count(), 1)):
|
||||
# get a new key
|
||||
key, subkey = jax.random.split(key)
|
||||
|
||||
encoded_images = p_generate(
|
||||
tokenized_prompt,
|
||||
shard_prng_key(subkey),
|
||||
self.params,
|
||||
GEN_TOP_K,
|
||||
GEN_TOP_P,
|
||||
TEMPERATURE,
|
||||
COND_SCALE,
|
||||
self.model
|
||||
)
|
||||
|
||||
# remove BOS
|
||||
encoded_images = encoded_images.sequences[..., 1:]
|
||||
|
||||
# decode images
|
||||
decoded_images = p_decode(self.vqgan, encoded_images, self.vqgan_params)
|
||||
decoded_images = decoded_images.clip(0.0, 1.0).reshape((-1, 256, 256, 3))
|
||||
for img in decoded_images:
|
||||
images.append(Image.fromarray(np.asarray(img * 255, dtype=np.uint8)))
|
||||
|
||||
return images
|
||||
|
||||
dallE = DalleModel(ModelSize.MINI)
|
36
api/alas/evaluators/dialog_gpt.py
Normal file
36
api/alas/evaluators/dialog_gpt.py
Normal file
|
@ -0,0 +1,36 @@
|
|||
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig
|
||||
|
||||
|
||||
class DialogGPT:
|
||||
def __init__(self):
|
||||
model_name = "microsoft/DialoGPT-large"
|
||||
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
self.model = AutoModelForCausalLM.from_pretrained(model_name)
|
||||
self.config = AutoConfig.from_pretrained(model_name)
|
||||
|
||||
self.config.save_pretrained(model_name)
|
||||
self.tokenizer.save_pretrained(model_name)
|
||||
self.model.save_pretrained(model_name)
|
||||
|
||||
def eval(self, text: str) -> str:
|
||||
# encode the new user input, add the eos_token and return a tensor in Pytorch
|
||||
new_user_input_ids = self.tokenizer.encode(text + self.tokenizer.eos_token, return_tensors='pt')
|
||||
|
||||
# generated a response
|
||||
chat_history_ids = self.model.generate(new_user_input_ids, pad_token_id=self.tokenizer.eos_token_id)
|
||||
|
||||
# pretty print last ouput tokens from bot
|
||||
return self.tokenizer.decode(chat_history_ids[:, new_user_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
||||
|
||||
# Preprocess text (username and link placeholders)
|
||||
def preprocess(self, text):
|
||||
new_text = []
|
||||
for t in text.split(" "):
|
||||
t = '@user' if t.startswith('@') and len(t) > 1 else t
|
||||
t = 'http' if t.startswith('http') else t
|
||||
new_text.append(t)
|
||||
return " ".join(new_text)
|
||||
|
||||
|
||||
dialogGPT = DialogGPT()
|
85
api/alas/evaluators/roberta.py
Normal file
85
api/alas/evaluators/roberta.py
Normal file
|
@ -0,0 +1,85 @@
|
|||
from transformers import AutoModelForSequenceClassification
|
||||
from transformers import AutoTokenizer, AutoConfig
|
||||
import numpy as np
|
||||
from scipy.special import softmax
|
||||
|
||||
|
||||
class Roberta:
|
||||
def __init__(self, model_name, labels=None):
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
||||
|
||||
self.config = AutoConfig.from_pretrained(model_name)
|
||||
|
||||
if labels:
|
||||
self.config.id2label = {
|
||||
idx: labels[idx]
|
||||
for idx in range(len(labels))
|
||||
}
|
||||
|
||||
self.config.label2id = {
|
||||
labels[idx]: idx
|
||||
for idx in range(len(labels))
|
||||
}
|
||||
|
||||
self.config.save_pretrained(model_name)
|
||||
self.tokenizer.save_pretrained(model_name)
|
||||
self.model.save_pretrained(model_name)
|
||||
|
||||
def eval(self, text: str) -> dict:
|
||||
text = self.preprocess(text)
|
||||
encoded_input = self.tokenizer(text, return_tensors='pt')
|
||||
output = self.model(**encoded_input)
|
||||
scores = output[0][0].detach().numpy()
|
||||
scores = softmax(scores)
|
||||
|
||||
ranking = np.argsort(scores)
|
||||
ranking = ranking[::-1]
|
||||
|
||||
return {self.config.id2label[ranking[i]]: scores[ranking[i]].item() for i in range(scores.shape[0])}
|
||||
|
||||
# Preprocess text (username and link placeholders)
|
||||
def preprocess(self, text):
|
||||
new_text = []
|
||||
for t in text.split(" "):
|
||||
t = '@user' if t.startswith('@') and len(t) > 1 else t
|
||||
t = 'http' if t.startswith('http') else t
|
||||
new_text.append(t)
|
||||
return " ".join(new_text)
|
||||
|
||||
|
||||
class Emotion(Roberta):
|
||||
def __init__(self):
|
||||
super().__init__("cardiffnlp/twitter-roberta-base-emotion",
|
||||
labels=["anger", "joy", "optimism", "sadness"])
|
||||
|
||||
|
||||
class Hate(Roberta):
|
||||
def __init__(self):
|
||||
super().__init__("cardiffnlp/twitter-roberta-base-hate",
|
||||
labels=["noHate", "hate"])
|
||||
|
||||
|
||||
class Irony(Roberta):
|
||||
def __init__(self):
|
||||
super().__init__("cardiffnlp/twitter-roberta-base-irony",
|
||||
labels=["noIrony", "irony"])
|
||||
|
||||
|
||||
class Offensive(Roberta):
|
||||
def __init__(self):
|
||||
super().__init__("cardiffnlp/twitter-roberta-base-offensive",
|
||||
labels=["noOffensive", "offensive"])
|
||||
|
||||
|
||||
class Sentiment(Roberta):
|
||||
def __init__(self):
|
||||
super().__init__("cardiffnlp/twitter-roberta-base-sentiment",
|
||||
labels=["negative", "neutral", "positive"])
|
||||
|
||||
|
||||
emotion = Emotion()
|
||||
hate = Hate()
|
||||
irony = Irony()
|
||||
offensive = Offensive()
|
||||
sentiment = Sentiment()
|
107
api/alas/main.py
Normal file
107
api/alas/main.py
Normal file
|
@ -0,0 +1,107 @@
|
|||
import uvicorn
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from evaluators import dialog_gpt
|
||||
from evaluators import roberta
|
||||
from evaluators.dalle import dalle
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
import time
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
origins = ["*"]
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
class RobertaEmotionResponse(BaseModel):
|
||||
joy: float
|
||||
sadness: float
|
||||
anger: float
|
||||
optimism: float
|
||||
|
||||
|
||||
@app.get("/roberta/emotion", response_model=RobertaEmotionResponse)
|
||||
def get_emotions(text: str) -> RobertaEmotionResponse:
|
||||
return roberta.emotion.eval(text)
|
||||
|
||||
|
||||
class RobertaHateResponse(BaseModel):
|
||||
noHate: float
|
||||
hate: float
|
||||
|
||||
|
||||
@app.get("/roberta/hate", response_model=RobertaHateResponse)
|
||||
def get_hate(text: str) -> RobertaHateResponse:
|
||||
return roberta.hate.eval(text)
|
||||
|
||||
|
||||
class RobertaIronyResponse(BaseModel):
|
||||
noIrony: float
|
||||
irony: float
|
||||
|
||||
|
||||
@app.get("/roberta/irony", response_model=RobertaIronyResponse)
|
||||
def get_irony(text: str) -> RobertaIronyResponse:
|
||||
return roberta.irony.eval(text)
|
||||
|
||||
|
||||
class RobertaOffensiveResponse(BaseModel):
|
||||
noOffensive: float
|
||||
offensive: float
|
||||
|
||||
|
||||
@app.get("/roberta/offensive", response_model=RobertaOffensiveResponse)
|
||||
def get_offensive(text: str) -> RobertaOffensiveResponse:
|
||||
return roberta.offensive.eval(text)
|
||||
|
||||
|
||||
class RobertaSentimentResponse(BaseModel):
|
||||
negative: float
|
||||
neutral: float
|
||||
positive: float
|
||||
|
||||
|
||||
@app.get("/roberta/sentiment", response_model=RobertaSentimentResponse)
|
||||
def get_sentiment(text: str) -> RobertaSentimentResponse:
|
||||
return roberta.sentiment.eval(text)
|
||||
|
||||
|
||||
@app.get("/dialog/continuation", response_model=str)
|
||||
def get_continuation(text: str) -> str:
|
||||
return dialog_gpt.dialogGPT.eval(text)
|
||||
|
||||
|
||||
@app.get("/dalle/generate")
|
||||
def get_image(text: str):
|
||||
text_prompt = text
|
||||
generated_imgs = dalle.dallE.eval(text_prompt, 2)
|
||||
|
||||
returned_generated_images = []
|
||||
dir_name = os.path.join("/home/armin/Desktop/dalle", f"{time.strftime('%Y-%m-%d_%H:%M:%S')}_{text_prompt}")
|
||||
Path(dir_name).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for idx, img in enumerate(generated_imgs):
|
||||
img.save(os.path.join(dir_name, f'{idx}.png'), format="png")
|
||||
|
||||
print(f"Created {2} images from text prompt [{text_prompt}]")
|
||||
|
||||
response = {'generatedImgs': returned_generated_images,
|
||||
'generatedImgsFormat': "img"}
|
||||
return response
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app)
|
1913
api/poetry.lock
generated
Normal file
1913
api/poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
22
api/pyproject.toml
Normal file
22
api/pyproject.toml
Normal file
|
@ -0,0 +1,22 @@
|
|||
[tool.poetry]
|
||||
name = "alas"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["Armin Friedl <dev@friedl.net>"]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.10,<3.11"
|
||||
fastapi = "^0.78.0"
|
||||
transformers = "^4.20.1"
|
||||
torch = "^1.11.0"
|
||||
scipy = "^1.8.1"
|
||||
dalle-mini = "^0.1.1"
|
||||
vqgan-jax = { git = "https://github.com/patil-suraj/vqgan-jax.git", branch = "main" }
|
||||
|
||||
[tool.poetry.dev-dependencies]
|
||||
pytest = "^5.2"
|
||||
uvicorn = "^0.18.2"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core>=1.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
0
api/tests/__init__.py
Normal file
0
api/tests/__init__.py
Normal file
5
api/tests/test_alas.py
Normal file
5
api/tests/test_alas.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
from alas_api import __version__
|
||||
|
||||
|
||||
def test_version():
|
||||
assert __version__ == '0.1.0'
|
3
web/.eslintrc.json
Normal file
3
web/.eslintrc.json
Normal file
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"extends": "next/core-web-vitals"
|
||||
}
|
32
web/.gitignore
vendored
Normal file
32
web/.gitignore
vendored
Normal file
|
@ -0,0 +1,32 @@
|
|||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# vercel
|
||||
.vercel
|
34
web/README.md
Normal file
34
web/README.md
Normal file
|
@ -0,0 +1,34 @@
|
|||
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
|
||||
|
||||
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
|
53
web/components/Continuation.tsx
Normal file
53
web/components/Continuation.tsx
Normal file
|
@ -0,0 +1,53 @@
|
|||
import {Col, Container, Row, Spinner} from "react-bootstrap";
|
||||
import {Configuration, DefaultApi} from "../service/openapi";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export default function Continuation(props) {
|
||||
let [continuation, setContinuation] = useState<string>("")
|
||||
let [computing, setComputing] = useState<boolean>(false)
|
||||
|
||||
|
||||
const configuration = new Configuration({
|
||||
basePath: 'http://localhost:8000'
|
||||
});
|
||||
|
||||
const api = new DefaultApi(configuration);
|
||||
const fetchContinuation = async () => {
|
||||
try {
|
||||
setComputing(true)
|
||||
let resp = await api.getContinuationDialogContinuationGet({text: props.text});
|
||||
setComputing(false)
|
||||
return resp;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchContinuation()
|
||||
.then(r => setContinuation(r));
|
||||
}, [props])
|
||||
|
||||
return (
|
||||
<Container className={"mt-5"}>
|
||||
<Row className={"justify-content-center mb-3"}>
|
||||
<h4 style={{width: "auto"}}>Effective Response</h4>
|
||||
</Row>
|
||||
<Row className={"justify-content-center"}>
|
||||
{computing
|
||||
? <Spinner animation="border" />
|
||||
: continuation && continuation !== "\"I\"" && continuation !== '""'
|
||||
? <figure style={{width: "auto"}}>
|
||||
<blockquote className="blockquote">
|
||||
<p>{continuation}</p>
|
||||
</blockquote>
|
||||
<figcaption className={"blockquote-footer"}>
|
||||
use at own risk
|
||||
</figcaption>
|
||||
</figure>
|
||||
: <p className={"text-muted"} style={{width: "auto"}}>Does not compute.</p>
|
||||
}
|
||||
</Row>
|
||||
</Container>
|
||||
);
|
||||
}
|
168
web/components/TextInput.tsx
Normal file
168
web/components/TextInput.tsx
Normal file
|
@ -0,0 +1,168 @@
|
|||
import { Configuration, DefaultApi, RobertaEmotionResponse, RobertaHateResponse, RobertaIronyResponse, RobertaOffensiveResponse, RobertaSentimentResponse } from "../service/openapi";
|
||||
import {Button, Card, Col, Container, Form, FormControl, FormGroup, Row, Table} from "react-bootstrap";
|
||||
import styles from "../styles/TextInput.module.scss";
|
||||
import {createRef, FormEvent, forwardRef, useCallback, useEffect, useState} from "react";
|
||||
import _ from "lodash";
|
||||
|
||||
|
||||
let debounce = _.debounce(async (fn) => await fn(), 400)
|
||||
|
||||
export default function TextInput(props) {
|
||||
const [text, setText] = useState("");
|
||||
const [emotions, setEmotions] = useState<RobertaEmotionResponse|undefined>(undefined);
|
||||
const [hate, setHate] = useState<RobertaHateResponse|undefined>(undefined);
|
||||
const [irony, setIrony] = useState<RobertaIronyResponse|undefined>(undefined);
|
||||
const [offensive, setOffensive] = useState<RobertaOffensiveResponse|undefined>(undefined);
|
||||
const [sentiment, setSentiment] = useState<RobertaSentimentResponse|undefined>(undefined);
|
||||
|
||||
useEffect(() => { debounce(async () => {
|
||||
props.textFn(text);
|
||||
await evaluateInput();
|
||||
}) }, [text])
|
||||
|
||||
const configuration = new Configuration({
|
||||
basePath: 'http://localhost:8000'
|
||||
});
|
||||
|
||||
const api = new DefaultApi(configuration);
|
||||
|
||||
let evaluateInput = async () => {
|
||||
if(!text) {
|
||||
setEmotions(undefined);
|
||||
setHate(undefined);
|
||||
setIrony(undefined);
|
||||
setOffensive(undefined);
|
||||
setSentiment(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
try{
|
||||
const [emotions, hate, irony, offensive, sentiment] = await Promise.all([
|
||||
api.getEmotionsRobertaEmotionGet({text: text}),
|
||||
api.getHateRobertaHateGet({ text: text }),
|
||||
api.getIronyRobertaIronyGet({ text: text }),
|
||||
api.getOffensiveRobertaOffensiveGet({ text: text }),
|
||||
api.getSentimentRobertaSentimentGet({ text: text })
|
||||
])
|
||||
|
||||
setEmotions(emotions);
|
||||
setHate(hate);
|
||||
setIrony(irony);
|
||||
setOffensive(offensive);
|
||||
setSentiment(sentiment);
|
||||
|
||||
} catch(error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Container fluid={true} className={"bg-primary pb-5"}>
|
||||
<Container className={"pb-5 pt-2"}>
|
||||
<Row xs={1} xl={2} className={"justify-content-center"}>
|
||||
<Col>
|
||||
<h1 className={`text-light`}>ALAS</h1>
|
||||
</Col>
|
||||
</Row>
|
||||
</Container>
|
||||
</Container>
|
||||
<Container>
|
||||
<Row xs={1} xl={2} className={`pb-5 justify-content-center`}>
|
||||
<Form className={styles.inputForm}>
|
||||
<FormGroup controlId="formText">
|
||||
<FormControl value={text}
|
||||
placeholder={"Start typing..."}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
className={styles.textBox} as="textarea" />
|
||||
</FormGroup>
|
||||
</Form>
|
||||
</Row>
|
||||
<Row className={"justify-content-center mb-3"}>
|
||||
<h4 style={{width: "auto"}}>Analysis</h4>
|
||||
</Row>
|
||||
<Row className={"justify-content-center gap-3"}>
|
||||
<Col className={"flex-grow-0"}>
|
||||
<Card style={{width: '18rem', height: '100%'}}>
|
||||
<Card.Body>
|
||||
<Card.Title className={"border-bottom border-2"}>
|
||||
Emotion
|
||||
</Card.Title>
|
||||
<Table size="sm" borderless={true}>
|
||||
<tbody>
|
||||
<tr className={"mt-2"}>
|
||||
<td>Joy</td>
|
||||
<td>{emotions?.joy.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Sadness</td>
|
||||
<td>{emotions?.sadness.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Anger</td>
|
||||
<td>{emotions?.anger.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Optimism</td>
|
||||
<td>{emotions?.optimism.toFixed(3)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</Table>
|
||||
</Card.Body>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col className={"flex-grow-0"}>
|
||||
<Card style={{width: '18rem', height: '100%'}}>
|
||||
<Card.Body>
|
||||
<Card.Title className={"border-bottom border-2"}>
|
||||
Temper
|
||||
</Card.Title>
|
||||
<Table size="sm" borderless={true}>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Hate</td>
|
||||
<td>{hate?.hate.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Irony</td>
|
||||
<td>{irony?.irony.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Offense</td>
|
||||
<td>{offensive?.offensive.toFixed(3)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</Table>
|
||||
</Card.Body>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col className={"flex-grow-0"}>
|
||||
<Card style={{width: '18rem', height: '100%'}}>
|
||||
<Card.Body>
|
||||
<Card.Title className={"border-bottom border-2"}>
|
||||
Sentiment
|
||||
</Card.Title>
|
||||
<Table size="sm" borderless={true}>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Negative</td>
|
||||
<td>{sentiment?.negative.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Neutral</td>
|
||||
<td>{sentiment?.neutral.toFixed(3)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Positive</td>
|
||||
<td>{sentiment?.positive.toFixed(3)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</Table>
|
||||
</Card.Body>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
5
web/next-env.d.ts
vendored
Normal file
5
web/next-env.d.ts
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
6
web/next.config.js
Normal file
6
web/next.config.js
Normal file
|
@ -0,0 +1,6 @@
|
|||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
}
|
||||
|
||||
module.exports = nextConfig
|
7
web/openapitools.json
Normal file
7
web/openapitools.json
Normal file
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
|
||||
"spaces": 2,
|
||||
"generator-cli": {
|
||||
"version": "6.0.0"
|
||||
}
|
||||
}
|
7343
web/package-lock.json
generated
Normal file
7343
web/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
28
web/package.json
Normal file
28
web/package.json
Normal file
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"name": "alas-web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"codegen": "rm -rf service/openapi; openapi-generator-cli generate -i http://localhost:8000/openapi.json -o service/openapi -g typescript-fetch --additional-properties=supportsES6=true,npmVersion=6.9.0,typescriptThreePlus=true"
|
||||
},
|
||||
"dependencies": {
|
||||
"bootstrap": "^5.1.3",
|
||||
"lodash": "^4.17.21",
|
||||
"next": "12.1.6",
|
||||
"react": "18.2.0",
|
||||
"react-bootstrap": "^2.4.0",
|
||||
"react-dom": "18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@openapitools/openapi-generator-cli": "^2.5.1",
|
||||
"@types/node": "^18.0.0",
|
||||
"@types/react": "^18.0.14",
|
||||
"eslint": "8.18.0",
|
||||
"eslint-config-next": "12.1.6",
|
||||
"sass": "^1.53.0"
|
||||
}
|
||||
}
|
5
web/pages/_about.tsx
Normal file
5
web/pages/_about.tsx
Normal file
|
@ -0,0 +1,5 @@
|
|||
function _about() {
|
||||
return <div>Test</div>
|
||||
}
|
||||
|
||||
export default _about
|
11
web/pages/_app.tsx
Normal file
11
web/pages/_app.tsx
Normal file
|
@ -0,0 +1,11 @@
|
|||
import '../styles/theme.scss'
|
||||
|
||||
// pages/_app.js
|
||||
|
||||
function MyApp({ Component, pageProps }) {
|
||||
return (
|
||||
<Component {...pageProps} />
|
||||
)
|
||||
}
|
||||
|
||||
export default MyApp
|
15
web/pages/_document.js
Normal file
15
web/pages/_document.js
Normal file
|
@ -0,0 +1,15 @@
|
|||
import NextDocument, {Html, Head, Main, NextScript} from 'next/document'
|
||||
|
||||
export default class Document extends NextDocument {
|
||||
render() {
|
||||
return (
|
||||
<Html lang='en'>
|
||||
<Head/>
|
||||
<body>
|
||||
<Main/>
|
||||
<NextScript/>
|
||||
</body>
|
||||
</Html>
|
||||
)
|
||||
}
|
||||
}
|
5
web/pages/api/hello.js
Normal file
5
web/pages/api/hello.js
Normal file
|
@ -0,0 +1,5 @@
|
|||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
|
||||
export default function handler(req, res) {
|
||||
res.status(200).json({ name: 'John Doe' })
|
||||
}
|
24
web/pages/index.tsx
Normal file
24
web/pages/index.tsx
Normal file
|
@ -0,0 +1,24 @@
|
|||
import Head from 'next/head'
|
||||
|
||||
import TextInput from "../components/TextInput";
|
||||
import Continuation from '../components/Continuation';
|
||||
import {useRef, useState} from "react";
|
||||
|
||||
export default function Home() {
|
||||
const [text, setText] = useState<string>("");
|
||||
|
||||
// @ts-ignore
|
||||
return (
|
||||
<div>
|
||||
<Head>
|
||||
<title>Alas, me got ye now</title>
|
||||
<meta name="description" content="Finally understand what people really say"/>
|
||||
<link rel="icon" href="/favicon.ico"/>
|
||||
</Head>
|
||||
|
||||
<TextInput textFn={setText} />
|
||||
|
||||
<Continuation text={text}/>
|
||||
</div>
|
||||
)
|
||||
}
|
BIN
web/public/favicon.ico
Normal file
BIN
web/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 25 KiB |
4
web/public/vercel.svg
Normal file
4
web/public/vercel.svg
Normal file
|
@ -0,0 +1,4 @@
|
|||
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
|
||||
</svg>
|
After Width: | Height: | Size: 1.1 KiB |
23
web/service/openapi/.openapi-generator-ignore
Normal file
23
web/service/openapi/.openapi-generator-ignore
Normal file
|
@ -0,0 +1,23 @@
|
|||
# OpenAPI Generator Ignore
|
||||
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
|
||||
|
||||
# Use this file to prevent files from being overwritten by the generator.
|
||||
# The patterns follow closely to .gitignore or .dockerignore.
|
||||
|
||||
# As an example, the C# client generator defines ApiClient.cs.
|
||||
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
|
||||
#ApiClient.cs
|
||||
|
||||
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
|
||||
#foo/*/qux
|
||||
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
|
||||
|
||||
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
|
||||
#foo/**/qux
|
||||
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
|
||||
|
||||
# You can also negate patterns with an exclamation (!).
|
||||
# For example, you can ignore all files in a docs folder with the file extension .md:
|
||||
#docs/*.md
|
||||
# Then explicitly reverse the ignore rule for a single file:
|
||||
#!docs/README.md
|
14
web/service/openapi/.openapi-generator/FILES
Normal file
14
web/service/openapi/.openapi-generator/FILES
Normal file
|
@ -0,0 +1,14 @@
|
|||
.openapi-generator-ignore
|
||||
apis/DefaultApi.ts
|
||||
apis/index.ts
|
||||
index.ts
|
||||
models/HTTPValidationError.ts
|
||||
models/LocationInner.ts
|
||||
models/RobertaEmotionResponse.ts
|
||||
models/RobertaHateResponse.ts
|
||||
models/RobertaIronyResponse.ts
|
||||
models/RobertaOffensiveResponse.ts
|
||||
models/RobertaSentimentResponse.ts
|
||||
models/ValidationError.ts
|
||||
models/index.ts
|
||||
runtime.ts
|
1
web/service/openapi/.openapi-generator/VERSION
Normal file
1
web/service/openapi/.openapi-generator/VERSION
Normal file
|
@ -0,0 +1 @@
|
|||
6.0.0
|
271
web/service/openapi/apis/DefaultApi.ts
Normal file
271
web/service/openapi/apis/DefaultApi.ts
Normal file
|
@ -0,0 +1,271 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
import * as runtime from '../runtime';
|
||||
import {
|
||||
HTTPValidationError,
|
||||
HTTPValidationErrorFromJSON,
|
||||
HTTPValidationErrorToJSON,
|
||||
RobertaEmotionResponse,
|
||||
RobertaEmotionResponseFromJSON,
|
||||
RobertaEmotionResponseToJSON,
|
||||
RobertaHateResponse,
|
||||
RobertaHateResponseFromJSON,
|
||||
RobertaHateResponseToJSON,
|
||||
RobertaIronyResponse,
|
||||
RobertaIronyResponseFromJSON,
|
||||
RobertaIronyResponseToJSON,
|
||||
RobertaOffensiveResponse,
|
||||
RobertaOffensiveResponseFromJSON,
|
||||
RobertaOffensiveResponseToJSON,
|
||||
RobertaSentimentResponse,
|
||||
RobertaSentimentResponseFromJSON,
|
||||
RobertaSentimentResponseToJSON,
|
||||
} from '../models';
|
||||
|
||||
export interface GetContinuationDialogContinuationGetRequest {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface GetEmotionsRobertaEmotionGetRequest {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface GetHateRobertaHateGetRequest {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface GetIronyRobertaIronyGetRequest {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface GetOffensiveRobertaOffensiveGetRequest {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface GetSentimentRobertaSentimentGetRequest {
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
export class DefaultApi extends runtime.BaseAPI {
|
||||
|
||||
/**
|
||||
* Get Continuation
|
||||
*/
|
||||
async getContinuationDialogContinuationGetRaw(requestParameters: GetContinuationDialogContinuationGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<runtime.ApiResponse<string>> {
|
||||
if (requestParameters.text === null || requestParameters.text === undefined) {
|
||||
throw new runtime.RequiredError('text','Required parameter requestParameters.text was null or undefined when calling getContinuationDialogContinuationGet.');
|
||||
}
|
||||
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters.text !== undefined) {
|
||||
queryParameters['text'] = requestParameters.text;
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
const response = await this.request({
|
||||
path: `/dialog/continuation`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.TextApiResponse(response) as any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Continuation
|
||||
*/
|
||||
async getContinuationDialogContinuationGet(requestParameters: GetContinuationDialogContinuationGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<string> {
|
||||
const response = await this.getContinuationDialogContinuationGetRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Emotions
|
||||
*/
|
||||
async getEmotionsRobertaEmotionGetRaw(requestParameters: GetEmotionsRobertaEmotionGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<runtime.ApiResponse<RobertaEmotionResponse>> {
|
||||
if (requestParameters.text === null || requestParameters.text === undefined) {
|
||||
throw new runtime.RequiredError('text','Required parameter requestParameters.text was null or undefined when calling getEmotionsRobertaEmotionGet.');
|
||||
}
|
||||
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters.text !== undefined) {
|
||||
queryParameters['text'] = requestParameters.text;
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
const response = await this.request({
|
||||
path: `/roberta/emotion`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) => RobertaEmotionResponseFromJSON(jsonValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Emotions
|
||||
*/
|
||||
async getEmotionsRobertaEmotionGet(requestParameters: GetEmotionsRobertaEmotionGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<RobertaEmotionResponse> {
|
||||
const response = await this.getEmotionsRobertaEmotionGetRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Hate
|
||||
*/
|
||||
async getHateRobertaHateGetRaw(requestParameters: GetHateRobertaHateGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<runtime.ApiResponse<RobertaHateResponse>> {
|
||||
if (requestParameters.text === null || requestParameters.text === undefined) {
|
||||
throw new runtime.RequiredError('text','Required parameter requestParameters.text was null or undefined when calling getHateRobertaHateGet.');
|
||||
}
|
||||
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters.text !== undefined) {
|
||||
queryParameters['text'] = requestParameters.text;
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
const response = await this.request({
|
||||
path: `/roberta/hate`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) => RobertaHateResponseFromJSON(jsonValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Hate
|
||||
*/
|
||||
async getHateRobertaHateGet(requestParameters: GetHateRobertaHateGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<RobertaHateResponse> {
|
||||
const response = await this.getHateRobertaHateGetRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Irony
|
||||
*/
|
||||
async getIronyRobertaIronyGetRaw(requestParameters: GetIronyRobertaIronyGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<runtime.ApiResponse<RobertaIronyResponse>> {
|
||||
if (requestParameters.text === null || requestParameters.text === undefined) {
|
||||
throw new runtime.RequiredError('text','Required parameter requestParameters.text was null or undefined when calling getIronyRobertaIronyGet.');
|
||||
}
|
||||
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters.text !== undefined) {
|
||||
queryParameters['text'] = requestParameters.text;
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
const response = await this.request({
|
||||
path: `/roberta/irony`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) => RobertaIronyResponseFromJSON(jsonValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Irony
|
||||
*/
|
||||
async getIronyRobertaIronyGet(requestParameters: GetIronyRobertaIronyGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<RobertaIronyResponse> {
|
||||
const response = await this.getIronyRobertaIronyGetRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Offensive
|
||||
*/
|
||||
async getOffensiveRobertaOffensiveGetRaw(requestParameters: GetOffensiveRobertaOffensiveGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<runtime.ApiResponse<RobertaOffensiveResponse>> {
|
||||
if (requestParameters.text === null || requestParameters.text === undefined) {
|
||||
throw new runtime.RequiredError('text','Required parameter requestParameters.text was null or undefined when calling getOffensiveRobertaOffensiveGet.');
|
||||
}
|
||||
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters.text !== undefined) {
|
||||
queryParameters['text'] = requestParameters.text;
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
const response = await this.request({
|
||||
path: `/roberta/offensive`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) => RobertaOffensiveResponseFromJSON(jsonValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Offensive
|
||||
*/
|
||||
async getOffensiveRobertaOffensiveGet(requestParameters: GetOffensiveRobertaOffensiveGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<RobertaOffensiveResponse> {
|
||||
const response = await this.getOffensiveRobertaOffensiveGetRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Sentiment
|
||||
*/
|
||||
async getSentimentRobertaSentimentGetRaw(requestParameters: GetSentimentRobertaSentimentGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<runtime.ApiResponse<RobertaSentimentResponse>> {
|
||||
if (requestParameters.text === null || requestParameters.text === undefined) {
|
||||
throw new runtime.RequiredError('text','Required parameter requestParameters.text was null or undefined when calling getSentimentRobertaSentimentGet.');
|
||||
}
|
||||
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters.text !== undefined) {
|
||||
queryParameters['text'] = requestParameters.text;
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
const response = await this.request({
|
||||
path: `/roberta/sentiment`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) => RobertaSentimentResponseFromJSON(jsonValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Sentiment
|
||||
*/
|
||||
async getSentimentRobertaSentimentGet(requestParameters: GetSentimentRobertaSentimentGetRequest, initOverrides?: RequestInit | runtime.InitOverideFunction): Promise<RobertaSentimentResponse> {
|
||||
const response = await this.getSentimentRobertaSentimentGetRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
}
|
||||
|
||||
}
|
3
web/service/openapi/apis/index.ts
Normal file
3
web/service/openapi/apis/index.ts
Normal file
|
@ -0,0 +1,3 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export * from './DefaultApi';
|
5
web/service/openapi/index.ts
Normal file
5
web/service/openapi/index.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export * from './runtime';
|
||||
export * from './apis';
|
||||
export * from './models';
|
63
web/service/openapi/models/HTTPValidationError.ts
Normal file
63
web/service/openapi/models/HTTPValidationError.ts
Normal file
|
@ -0,0 +1,63 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
import {
|
||||
ValidationError,
|
||||
ValidationErrorFromJSON,
|
||||
ValidationErrorFromJSONTyped,
|
||||
ValidationErrorToJSON,
|
||||
} from './ValidationError';
|
||||
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface HTTPValidationError
|
||||
*/
|
||||
export interface HTTPValidationError {
|
||||
/**
|
||||
*
|
||||
* @type {Array<ValidationError>}
|
||||
* @memberof HTTPValidationError
|
||||
*/
|
||||
detail?: Array<ValidationError>;
|
||||
}
|
||||
|
||||
export function HTTPValidationErrorFromJSON(json: any): HTTPValidationError {
|
||||
return HTTPValidationErrorFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function HTTPValidationErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): HTTPValidationError {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'detail': !exists(json, 'detail') ? undefined : ((json['detail'] as Array<any>).map(ValidationErrorFromJSON)),
|
||||
};
|
||||
}
|
||||
|
||||
export function HTTPValidationErrorToJSON(value?: HTTPValidationError | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'detail': value.detail === undefined ? undefined : ((value.detail as Array<any>).map(ValidationErrorToJSON)),
|
||||
};
|
||||
}
|
||||
|
35
web/service/openapi/models/LocationInner.ts
Normal file
35
web/service/openapi/models/LocationInner.ts
Normal file
|
@ -0,0 +1,35 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface LocationInner
|
||||
*/
|
||||
export interface LocationInner {
|
||||
}
|
||||
|
||||
export function LocationInnerFromJSON(json: any): LocationInner {
|
||||
return LocationInnerFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function LocationInnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): LocationInner {
|
||||
return json;
|
||||
}
|
||||
|
||||
export function LocationInnerToJSON(value?: LocationInner | null): any {
|
||||
return value;
|
||||
}
|
||||
|
80
web/service/openapi/models/RobertaEmotionResponse.ts
Normal file
80
web/service/openapi/models/RobertaEmotionResponse.ts
Normal file
|
@ -0,0 +1,80 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface RobertaEmotionResponse
|
||||
*/
|
||||
export interface RobertaEmotionResponse {
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaEmotionResponse
|
||||
*/
|
||||
joy: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaEmotionResponse
|
||||
*/
|
||||
sadness: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaEmotionResponse
|
||||
*/
|
||||
anger: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaEmotionResponse
|
||||
*/
|
||||
optimism: number;
|
||||
}
|
||||
|
||||
export function RobertaEmotionResponseFromJSON(json: any): RobertaEmotionResponse {
|
||||
return RobertaEmotionResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function RobertaEmotionResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): RobertaEmotionResponse {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'joy': json['joy'],
|
||||
'sadness': json['sadness'],
|
||||
'anger': json['anger'],
|
||||
'optimism': json['optimism'],
|
||||
};
|
||||
}
|
||||
|
||||
export function RobertaEmotionResponseToJSON(value?: RobertaEmotionResponse | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'joy': value.joy,
|
||||
'sadness': value.sadness,
|
||||
'anger': value.anger,
|
||||
'optimism': value.optimism,
|
||||
};
|
||||
}
|
||||
|
64
web/service/openapi/models/RobertaHateResponse.ts
Normal file
64
web/service/openapi/models/RobertaHateResponse.ts
Normal file
|
@ -0,0 +1,64 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface RobertaHateResponse
|
||||
*/
|
||||
export interface RobertaHateResponse {
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaHateResponse
|
||||
*/
|
||||
noHate: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaHateResponse
|
||||
*/
|
||||
hate: number;
|
||||
}
|
||||
|
||||
export function RobertaHateResponseFromJSON(json: any): RobertaHateResponse {
|
||||
return RobertaHateResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function RobertaHateResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): RobertaHateResponse {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'noHate': json['noHate'],
|
||||
'hate': json['hate'],
|
||||
};
|
||||
}
|
||||
|
||||
export function RobertaHateResponseToJSON(value?: RobertaHateResponse | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'noHate': value.noHate,
|
||||
'hate': value.hate,
|
||||
};
|
||||
}
|
||||
|
64
web/service/openapi/models/RobertaIronyResponse.ts
Normal file
64
web/service/openapi/models/RobertaIronyResponse.ts
Normal file
|
@ -0,0 +1,64 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface RobertaIronyResponse
|
||||
*/
|
||||
export interface RobertaIronyResponse {
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaIronyResponse
|
||||
*/
|
||||
noIrony: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaIronyResponse
|
||||
*/
|
||||
irony: number;
|
||||
}
|
||||
|
||||
export function RobertaIronyResponseFromJSON(json: any): RobertaIronyResponse {
|
||||
return RobertaIronyResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function RobertaIronyResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): RobertaIronyResponse {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'noIrony': json['noIrony'],
|
||||
'irony': json['irony'],
|
||||
};
|
||||
}
|
||||
|
||||
export function RobertaIronyResponseToJSON(value?: RobertaIronyResponse | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'noIrony': value.noIrony,
|
||||
'irony': value.irony,
|
||||
};
|
||||
}
|
||||
|
64
web/service/openapi/models/RobertaOffensiveResponse.ts
Normal file
64
web/service/openapi/models/RobertaOffensiveResponse.ts
Normal file
|
@ -0,0 +1,64 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface RobertaOffensiveResponse
|
||||
*/
|
||||
export interface RobertaOffensiveResponse {
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaOffensiveResponse
|
||||
*/
|
||||
noOffensive: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaOffensiveResponse
|
||||
*/
|
||||
offensive: number;
|
||||
}
|
||||
|
||||
export function RobertaOffensiveResponseFromJSON(json: any): RobertaOffensiveResponse {
|
||||
return RobertaOffensiveResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function RobertaOffensiveResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): RobertaOffensiveResponse {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'noOffensive': json['noOffensive'],
|
||||
'offensive': json['offensive'],
|
||||
};
|
||||
}
|
||||
|
||||
export function RobertaOffensiveResponseToJSON(value?: RobertaOffensiveResponse | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'noOffensive': value.noOffensive,
|
||||
'offensive': value.offensive,
|
||||
};
|
||||
}
|
||||
|
72
web/service/openapi/models/RobertaSentimentResponse.ts
Normal file
72
web/service/openapi/models/RobertaSentimentResponse.ts
Normal file
|
@ -0,0 +1,72 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface RobertaSentimentResponse
|
||||
*/
|
||||
export interface RobertaSentimentResponse {
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaSentimentResponse
|
||||
*/
|
||||
negative: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaSentimentResponse
|
||||
*/
|
||||
neutral: number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof RobertaSentimentResponse
|
||||
*/
|
||||
positive: number;
|
||||
}
|
||||
|
||||
export function RobertaSentimentResponseFromJSON(json: any): RobertaSentimentResponse {
|
||||
return RobertaSentimentResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function RobertaSentimentResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): RobertaSentimentResponse {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'negative': json['negative'],
|
||||
'neutral': json['neutral'],
|
||||
'positive': json['positive'],
|
||||
};
|
||||
}
|
||||
|
||||
export function RobertaSentimentResponseToJSON(value?: RobertaSentimentResponse | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'negative': value.negative,
|
||||
'neutral': value.neutral,
|
||||
'positive': value.positive,
|
||||
};
|
||||
}
|
||||
|
79
web/service/openapi/models/ValidationError.ts
Normal file
79
web/service/openapi/models/ValidationError.ts
Normal file
|
@ -0,0 +1,79 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { exists, mapValues } from '../runtime';
|
||||
import {
|
||||
LocationInner,
|
||||
LocationInnerFromJSON,
|
||||
LocationInnerFromJSONTyped,
|
||||
LocationInnerToJSON,
|
||||
} from './LocationInner';
|
||||
|
||||
/**
|
||||
*
|
||||
* @export
|
||||
* @interface ValidationError
|
||||
*/
|
||||
export interface ValidationError {
|
||||
/**
|
||||
*
|
||||
* @type {Array<LocationInner>}
|
||||
* @memberof ValidationError
|
||||
*/
|
||||
loc: Array<LocationInner>;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ValidationError
|
||||
*/
|
||||
msg: string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ValidationError
|
||||
*/
|
||||
type: string;
|
||||
}
|
||||
|
||||
export function ValidationErrorFromJSON(json: any): ValidationError {
|
||||
return ValidationErrorFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ValidationErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): ValidationError {
|
||||
if ((json === undefined) || (json === null)) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'loc': ((json['loc'] as Array<any>).map(LocationInnerFromJSON)),
|
||||
'msg': json['msg'],
|
||||
'type': json['type'],
|
||||
};
|
||||
}
|
||||
|
||||
export function ValidationErrorToJSON(value?: ValidationError | null): any {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
|
||||
'loc': ((value.loc as Array<any>).map(LocationInnerToJSON)),
|
||||
'msg': value.msg,
|
||||
'type': value.type,
|
||||
};
|
||||
}
|
||||
|
10
web/service/openapi/models/index.ts
Normal file
10
web/service/openapi/models/index.ts
Normal file
|
@ -0,0 +1,10 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export * from './HTTPValidationError';
|
||||
export * from './LocationInner';
|
||||
export * from './RobertaEmotionResponse';
|
||||
export * from './RobertaHateResponse';
|
||||
export * from './RobertaIronyResponse';
|
||||
export * from './RobertaOffensiveResponse';
|
||||
export * from './RobertaSentimentResponse';
|
||||
export * from './ValidationError';
|
369
web/service/openapi/runtime.ts
Normal file
369
web/service/openapi/runtime.ts
Normal file
|
@ -0,0 +1,369 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* FastAPI
|
||||
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
*
|
||||
* The version of the OpenAPI document: 0.1.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export const BASE_PATH = "http://localhost".replace(/\/+$/, "");
|
||||
|
||||
export interface ConfigurationParameters {
|
||||
basePath?: string; // override base path
|
||||
fetchApi?: FetchAPI; // override for fetch implementation
|
||||
middleware?: Middleware[]; // middleware to apply before/after fetch requests
|
||||
queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
|
||||
username?: string; // parameter for basic security
|
||||
password?: string; // parameter for basic security
|
||||
apiKey?: string | ((name: string) => string); // parameter for apiKey security
|
||||
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
|
||||
headers?: HTTPHeaders; //header params we want to use on every request
|
||||
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
|
||||
}
|
||||
|
||||
export class Configuration {
|
||||
constructor(private configuration: ConfigurationParameters = {}) {}
|
||||
|
||||
set config(configuration: Configuration) {
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
get basePath(): string {
|
||||
return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
|
||||
}
|
||||
|
||||
get fetchApi(): FetchAPI | undefined {
|
||||
return this.configuration.fetchApi;
|
||||
}
|
||||
|
||||
get middleware(): Middleware[] {
|
||||
return this.configuration.middleware || [];
|
||||
}
|
||||
|
||||
get queryParamsStringify(): (params: HTTPQuery) => string {
|
||||
return this.configuration.queryParamsStringify || querystring;
|
||||
}
|
||||
|
||||
get username(): string | undefined {
|
||||
return this.configuration.username;
|
||||
}
|
||||
|
||||
get password(): string | undefined {
|
||||
return this.configuration.password;
|
||||
}
|
||||
|
||||
get apiKey(): ((name: string) => string) | undefined {
|
||||
const apiKey = this.configuration.apiKey;
|
||||
if (apiKey) {
|
||||
return typeof apiKey === 'function' ? apiKey : () => apiKey;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get accessToken(): ((name?: string, scopes?: string[]) => string | Promise<string>) | undefined {
|
||||
const accessToken = this.configuration.accessToken;
|
||||
if (accessToken) {
|
||||
return typeof accessToken === 'function' ? accessToken : async () => accessToken;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get headers(): HTTPHeaders | undefined {
|
||||
return this.configuration.headers;
|
||||
}
|
||||
|
||||
get credentials(): RequestCredentials | undefined {
|
||||
return this.configuration.credentials;
|
||||
}
|
||||
}
|
||||
|
||||
export const DefaultConfig = new Configuration();
|
||||
|
||||
/**
|
||||
* This is the base class for all generated API classes.
|
||||
*/
|
||||
export class BaseAPI {
|
||||
|
||||
private middleware: Middleware[];
|
||||
|
||||
constructor(protected configuration = DefaultConfig) {
|
||||
this.middleware = configuration.middleware;
|
||||
}
|
||||
|
||||
withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
|
||||
const next = this.clone<T>();
|
||||
next.middleware = next.middleware.concat(...middlewares);
|
||||
return next;
|
||||
}
|
||||
|
||||
withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
|
||||
const middlewares = preMiddlewares.map((pre) => ({ pre }));
|
||||
return this.withMiddleware<T>(...middlewares);
|
||||
}
|
||||
|
||||
withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
|
||||
const middlewares = postMiddlewares.map((post) => ({ post }));
|
||||
return this.withMiddleware<T>(...middlewares);
|
||||
}
|
||||
|
||||
protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverideFunction): Promise<Response> {
|
||||
const { url, init } = await this.createFetchParams(context, initOverrides);
|
||||
const response = await this.fetchApi(url, init);
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
return response;
|
||||
}
|
||||
throw new ResponseError(response, 'Response returned an error code');
|
||||
}
|
||||
|
||||
private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverideFunction) {
|
||||
let url = this.configuration.basePath + context.path;
|
||||
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
|
||||
// only add the querystring to the URL if there are query parameters.
|
||||
// this is done to avoid urls ending with a "?" character which buggy webservers
|
||||
// do not handle correctly sometimes.
|
||||
url += '?' + this.configuration.queryParamsStringify(context.query);
|
||||
}
|
||||
|
||||
const headers = Object.assign({}, this.configuration.headers, context.headers);
|
||||
Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
|
||||
|
||||
const initOverrideFn =
|
||||
typeof initOverrides === "function"
|
||||
? initOverrides
|
||||
: async () => initOverrides;
|
||||
|
||||
const initParams = {
|
||||
method: context.method,
|
||||
headers,
|
||||
body: context.body,
|
||||
credentials: this.configuration.credentials,
|
||||
};
|
||||
|
||||
const overridedInit: RequestInit = {
|
||||
...initParams,
|
||||
...(await initOverrideFn({
|
||||
init: initParams,
|
||||
context,
|
||||
}))
|
||||
}
|
||||
|
||||
const init: RequestInit = {
|
||||
...overridedInit,
|
||||
body:
|
||||
isFormData(overridedInit.body) ||
|
||||
overridedInit.body instanceof URLSearchParams ||
|
||||
isBlob(overridedInit.body)
|
||||
? overridedInit.body
|
||||
: JSON.stringify(overridedInit.body),
|
||||
};
|
||||
|
||||
return { url, init };
|
||||
}
|
||||
|
||||
private fetchApi = async (url: string, init: RequestInit) => {
|
||||
let fetchParams = { url, init };
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.pre) {
|
||||
fetchParams = await middleware.pre({
|
||||
fetch: this.fetchApi,
|
||||
...fetchParams,
|
||||
}) || fetchParams;
|
||||
}
|
||||
}
|
||||
let response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.post) {
|
||||
response = await middleware.post({
|
||||
fetch: this.fetchApi,
|
||||
url: fetchParams.url,
|
||||
init: fetchParams.init,
|
||||
response: response.clone(),
|
||||
}) || response;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shallow clone of `this` by constructing a new instance
|
||||
* and then shallow cloning data members.
|
||||
*/
|
||||
private clone<T extends BaseAPI>(this: T): T {
|
||||
const constructor = this.constructor as any;
|
||||
const next = new constructor(this.configuration);
|
||||
next.middleware = this.middleware.slice();
|
||||
return next;
|
||||
}
|
||||
};
|
||||
|
||||
function isBlob(value: any): value is Blob {
|
||||
return typeof Blob !== 'undefined' && value instanceof Blob
|
||||
}
|
||||
|
||||
function isFormData(value: any): value is FormData {
|
||||
return typeof FormData !== "undefined" && value instanceof FormData
|
||||
}
|
||||
|
||||
export class ResponseError extends Error {
|
||||
name: "ResponseError" = "ResponseError";
|
||||
constructor(public response: Response, msg?: string) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
|
||||
export class RequiredError extends Error {
|
||||
name: "RequiredError" = "RequiredError";
|
||||
constructor(public field: string, msg?: string) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
|
||||
export const COLLECTION_FORMATS = {
|
||||
csv: ",",
|
||||
ssv: " ",
|
||||
tsv: "\t",
|
||||
pipes: "|",
|
||||
};
|
||||
|
||||
export type FetchAPI = WindowOrWorkerGlobalScope['fetch'];
|
||||
|
||||
export type Json = any;
|
||||
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
||||
export type HTTPHeaders = { [key: string]: string };
|
||||
export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery };
|
||||
export type HTTPBody = Json | FormData | URLSearchParams;
|
||||
export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }
|
||||
export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';
|
||||
|
||||
export type InitOverideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>
|
||||
|
||||
export interface FetchParams {
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
}
|
||||
|
||||
export interface RequestOpts {
|
||||
path: string;
|
||||
method: HTTPMethod;
|
||||
headers: HTTPHeaders;
|
||||
query?: HTTPQuery;
|
||||
body?: HTTPBody;
|
||||
}
|
||||
|
||||
export function exists(json: any, key: string) {
|
||||
const value = json[key];
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
export function querystring(params: HTTPQuery, prefix: string = ''): string {
|
||||
return Object.keys(params)
|
||||
.map(key => querystringSingleKey(key, params[key], prefix))
|
||||
.filter(part => part.length > 0)
|
||||
.join('&');
|
||||
}
|
||||
|
||||
function querystringSingleKey(key: string, value: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery, keyPrefix: string = ''): string {
|
||||
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
|
||||
if (value instanceof Array) {
|
||||
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
|
||||
.join(`&${encodeURIComponent(fullKey)}=`);
|
||||
return `${encodeURIComponent(fullKey)}=${multiValue}`;
|
||||
}
|
||||
if (value instanceof Set) {
|
||||
const valueAsArray = Array.from(value);
|
||||
return querystringSingleKey(key, valueAsArray, keyPrefix);
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
|
||||
}
|
||||
if (value instanceof Object) {
|
||||
return querystring(value as HTTPQuery, fullKey);
|
||||
}
|
||||
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
|
||||
}
|
||||
|
||||
export function mapValues(data: any, fn: (item: any) => any) {
|
||||
return Object.keys(data).reduce(
|
||||
(acc, key) => ({ ...acc, [key]: fn(data[key]) }),
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
export function canConsumeForm(consumes: Consume[]): boolean {
|
||||
for (const consume of consumes) {
|
||||
if ('multipart/form-data' === consume.contentType) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface Consume {
|
||||
contentType: string
|
||||
}
|
||||
|
||||
export interface RequestContext {
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
}
|
||||
|
||||
export interface ResponseContext {
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
response: Response;
|
||||
}
|
||||
|
||||
export interface Middleware {
|
||||
pre?(context: RequestContext): Promise<FetchParams | void>;
|
||||
post?(context: ResponseContext): Promise<Response | void>;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
raw: Response;
|
||||
value(): Promise<T>;
|
||||
}
|
||||
|
||||
export interface ResponseTransformer<T> {
|
||||
(json: any): T;
|
||||
}
|
||||
|
||||
export class JSONApiResponse<T> {
|
||||
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) {}
|
||||
|
||||
async value(): Promise<T> {
|
||||
return this.transformer(await this.raw.json());
|
||||
}
|
||||
}
|
||||
|
||||
export class VoidApiResponse {
|
||||
constructor(public raw: Response) {}
|
||||
|
||||
async value(): Promise<void> {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export class BlobApiResponse {
|
||||
constructor(public raw: Response) {}
|
||||
|
||||
async value(): Promise<Blob> {
|
||||
return await this.raw.blob();
|
||||
};
|
||||
}
|
||||
|
||||
export class TextApiResponse {
|
||||
constructor(public raw: Response) {}
|
||||
|
||||
async value(): Promise<string> {
|
||||
return await this.raw.text();
|
||||
};
|
||||
}
|
14
web/styles/TextInput.module.scss
Normal file
14
web/styles/TextInput.module.scss
Normal file
|
@ -0,0 +1,14 @@
|
|||
.inputForm {
|
||||
margin-top: -70px;
|
||||
}
|
||||
|
||||
.textBox {
|
||||
height: 200px;
|
||||
font-family: Nunito;
|
||||
}
|
||||
|
||||
@media (max-height: 600px) {
|
||||
.textBox {
|
||||
height: 100px;
|
||||
}
|
||||
}
|
18
web/styles/theme.scss
Normal file
18
web/styles/theme.scss
Normal file
|
@ -0,0 +1,18 @@
|
|||
/*! Themestr.app `Herbie` Bootstrap 4.3.1 theme */
|
||||
@import url(https://fonts.googleapis.com/css?family=Nunito:200,300,400,700);
|
||||
$font-family-base:Nunito;
|
||||
@import url(https://fonts.googleapis.com/css?family=Crete+Round:200,300,400,700);
|
||||
$headings-font-family:Crete Round;
|
||||
|
||||
$primary:#083358;
|
||||
$secondary:#F67280;
|
||||
$success:#0074E4;
|
||||
$danger:#FF4057;
|
||||
$info:#74DBEF;
|
||||
$warning:#FC3C3C;
|
||||
$light:#F2F2F0;
|
||||
$dark:#072247;
|
||||
|
||||
@import "~bootstrap/scss/bootstrap.scss";
|
||||
|
||||
// Add SASS theme customizations here..
|
30
web/tsconfig.json
Normal file
30
web/tsconfig.json
Normal file
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"incremental": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"moduleResolution": "nodenext"
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
Loading…
Reference in a new issue