Skip to content

Commit

Permalink
BACKUP
Browse files Browse the repository at this point in the history
  • Loading branch information
kjurl committed Dec 5, 2023
1 parent 6bbb143 commit c06e3cc
Show file tree
Hide file tree
Showing 24 changed files with 476 additions and 2,153 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Learn more about the power of Turborepo:

---

> 🚀 **Seasoned astronaut** Having fun!
> 🚀 **Project Badges** !
![Vercel deployments](https://img.shields.io/github/deployments/tokcide/website/production?label=vercel&logo=vercel&style=for-the-badge)
![]()
Expand Down
73 changes: 0 additions & 73 deletions api/python/codecheckr/index.py

This file was deleted.

3 changes: 0 additions & 3 deletions api/python/codecheckr/requirements.txt

This file was deleted.

11 changes: 0 additions & 11 deletions api/python/test/index.py

This file was deleted.

1 change: 0 additions & 1 deletion api/python/test/requirements.txt

This file was deleted.

39 changes: 15 additions & 24 deletions astro.config.mjs
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
import { defineConfig } from "astro/config";
// adapter
import vercel from "@astrojs/vercel/serverless";
// vite
import { ValidateEnv } from "vite-plugin-validate-env";
// integrations
import mdx from "@astrojs/mdx";
import prefetch from "@astrojs/prefetch";
import solidJs from "@astrojs/solid-js";
import vercel from "@astrojs/vercel/serverless";
import prefetch from "@astrojs/prefetch";
import unocss from "unocss/astro";
import { presetAttributify, presetIcons, presetUno, transformerDirectives, transformerVariantGroup } from "unocss";

import { presetDaisy } from "unocss-preset-daisy";
import { presetHeadlessUi } from "unocss-preset-primitives";

import { ValidateEnv } from "vite-plugin-validate-env";
// import tsconfigPaths from "vite-tsconfig-paths";
import { defineConfig } from "astro/config";
// https://astro.build/config
export default defineConfig({
site: "https://www.kanishkk.vercel.app",
output: "server",
adapter: vercel({
webAnalytics: {
enabled: true,
},
speedInsights: {
enabled: true,
},
webAnalytics: { enabled: true },
speedInsights: { enabled: true },
imageService: true,
functionPerRoute: false,
}),
vite: {
build: { external: ["xlsx"] },
// plugins: [ValidateEnv()],
},
integrations: [
solidJs(),
prefetch({ throttle: 3 }),
mdx({
syntaxHighlight: "shiki",
shikiConfig: { theme: "dracula" },
Expand All @@ -34,7 +37,6 @@ export default defineConfig({
}),
unocss({
injectReset: true,

shortcuts: [{ "i-logo": "i-logos-astro w-6em h-6em transform transition-800" }],
presets: [
presetUno({
Expand All @@ -61,16 +63,5 @@ export default defineConfig({
],
transformers: [transformerDirectives(), transformerVariantGroup()],
}),
prefetch({
// Allow up to three links to be prefetched concurrently
throttle: 3,
}),
solidJs(),
],
vite: {
build: {
external: ["xlsx"],
},
// plugins: [ValidateEnv()],
},
});
4 changes: 3 additions & 1 deletion backend/controllers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import typing as t

Routers = t.Set[t.Literal["codecheckr"] | t.Literal["instagram"] | t.Literal["xtra"]]
Routers = t.Set[
t.Union[t.Literal["codecheckr"], t.Literal["instagram"], t.Literal["xtra"]]
]
8 changes: 3 additions & 5 deletions backend/controllers/codecheckr.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@
from fastapi_class import View


@View(checkRouter := APIRouter(prefix="/check", tags=["Code Checkr"]))
class TestView:
@View(checkRouter := APIRouter(prefix="/codecheckr", tags=["Code Checkr"]))
class checkrView:
def get(self):
return {"command": "success"}
return {"service": "working"}

async def post(self, f: UploadFile = File(...)):
if (f is None) or (f.content_type != "application/zip"):
raise ValueError
v = await f.read()
retval = []
codes_fings: list[copydetect.CodeFingerprint] = []
Expand Down
12 changes: 12 additions & 0 deletions backend/controllers/facerecog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from fastapi import APIRouter
from fastapi_class import View


@View(recogRouter := APIRouter(prefix="/facerecog", tags=["Face Recognition"]))
class recogView:
def get(self):
return {"service": "not working"}


router = APIRouter()
router.include_router(recogRouter)
85 changes: 49 additions & 36 deletions backend/init_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import importlib
import inspect
import json
import os
import typing as t
from glob import glob

from fastapi import APIRouter, FastAPI
from fastapi.background import P
from tortoise.contrib.fastapi import register_tortoise

from .controllers import Routers
Expand All @@ -17,26 +19,46 @@


class App:
def __init__(self, base: t.Optional[str]) -> None:
def __init__(self, base: str) -> None:
# get importing path
if base:
self._base_url = base
else:
self._base_url = "/" + (
inspect.stack()[-1]
.filename.split("website", 1)[-1]
.rstrip(".py")
.rstrip("/index")
) # dont use complex "index" files
self._base_url = base

self._app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
configure_middlewares(self._app)
self._app.add_exception_handler(APIException, on_api_exception)
self._app.add_exception_handler(APIException, unhandled_exception_handler)

def _get_file_list(
self, subdir: str = "controllers"
) -> t.Generator[File, None, None]:
@classmethod
def from_file(cls, file: str, vercel_json: bool = False):
current_file = os.path.abspath(file)
index = current_file.rfind("api")

if index != -1:
path_from_string = current_file[index - 1 :]
else:
raise ValueError("The string 'api' was not found in the file path.")

base_string = path_from_string.rstrip(".py").rstrip("index").rstrip("/")

if not vercel_json:
return cls(base_string)

with open("./vercel.json") as f:
rewrites: t.List[
t.Dict[t.Literal["destination"] | t.Literal["source"], str]
] = json.load(f).get("rewrites", [])

# goto last slash and take string before slash
for m in rewrites:
if base_string == m["destination"]:
src = m["source"]
if (idx := src.rfind("/")) != -1:
base_string = src[:idx] # updated from rewrites
# complex regexes are not possible
return cls(base_string)

@staticmethod
def _get_file_list(subdir: str) -> t.Generator[File, None, None]:
"""access files in a subdir inside backend"""
PROJECT_ROOT = os.path.dirname(__file__)
APPS_MODULE = ".".join(["backend", subdir])
Expand All @@ -50,14 +72,6 @@ def _get_file_list(
def app(self):
return self._app

def title(self, t: str, /):
self._app.title = t
return self

def description(self, t: str, /):
self._app.description = t
return self

def docs(self):
self._app.docs_url = self._base_url + "/docs"
self._app.openapi_url = self._base_url + "/openapi.json"
Expand All @@ -80,28 +94,27 @@ def controllers(self, ct: Routers) -> App:
self._ct = ct
self.mainRouter = APIRouter()

PROJECT_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir)
)
PROJECT_ROOT = os.path.dirname(__file__)
APPS_MODULE = "backend.controllers"
pth = os.path.join(PROJECT_ROOT, os.path.basename("controllers"), "**.py")
for f in glob(pth):
if f.find("__init__.py") != -1:
for f in self._get_file_list("controllers"):
if f.path.find("__init__.py") != -1:
continue
name = os.path.basename(f).rstrip(".py")
if name not in ct:
if f.name not in ct:
continue

module = ".".join([APPS_MODULE, name])

# condition for database
rt = getattr(importlib.import_module(module), "router", None)
rt = getattr(importlib.import_module(f.import_string), "router", None)
if rt is not None:
print("router added")
self.mainRouter.include_router(rt, prefix=f"/{name}")
self.mainRouter.include_router(rt)
return self

def attach_controllers(self):
self._app.include_router(self.mainRouter, prefix=self._base_url)

@self._app.get(self._base_url)
def basic():
return {
"service": "UP",
"base_url": self._base_url,
"controllers": self._ct,
}

return self
22 changes: 16 additions & 6 deletions backend/middlewares.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
import time

from asgi_correlation_id import CorrelationIdMiddleware
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi_utils.timing import add_timing_middleware

from .prefs import settings


def configure_middlewares(app: FastAPI) -> None:
add_timing_middleware(app, prefix="app")
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response

app.add_middleware(CorrelationIdMiddleware)

add_cors_middleware(app)

if settings.PRODUCTION:
app.add_middleware(HTTPSRedirectMiddleware)


def add_cors_middleware(app: FastAPI, /):
app.add_middleware(CorrelationIdMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_origins_regex=settings.CORS_REGEX_ORIGINS,
allow_origin_regex=settings.CORS_REGEX_ORIGINS,
allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
allow_methods=settings.CORS_ALLOW_METHODS,
allow_headers=settings.CORS_ALLOW_HEADERS,
expose_headers=["X-Request-ID"],
expose_headers=["X-Request-ID", "X-Process-Time"],
)
Loading

0 comments on commit c06e3cc

Please sign in to comment.