Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Frontend #5

Merged
merged 3 commits into from
Feb 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
!.github
!.pre-commit-config.yaml
!.python-version
!.gitignore

requirements*.lock

Expand Down
62 changes: 60 additions & 2 deletions backend/src/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import logging
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
import httpx
from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware

from shared.logger import configure_logging
Expand All @@ -11,20 +13,76 @@
async def lifespan(_: FastAPI):
configure_logging()
yield
await ctx.close_client()


app = FastAPI(lifespan=lifespan)
logger = logging.getLogger("app")

app.add_middleware(
CORSMiddleware,
allow_origins=[], # TODO
allow_origins=[
"http://localhost:5173",
"http://127.0.0.1:5173",
"http://0.0.0.0:5173",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


class Context:
def __init__(self) -> None:
self.http_client = httpx.AsyncClient()
self.scraper_url = os.getenv("SCRAPER_URL")

async def close_client(self) -> None:
await self.http_client.aclose()


ctx = Context()


@app.post(
"/scrape/{page}/{amount}",
summary="Scrape certain amount of images",
status_code=status.HTTP_200_OK,
)
async def scrape(page: int, amount: int) -> None:
await ctx.http_client.post(
f"{ctx.scraper_url}/scrape/{page}/{amount}", timeout=None
)
return {"message": f"Scraped {amount} images"}


@app.get(
"/color_search/{color}",
summary="Search images by color",
status_code=status.HTTP_501_NOT_IMPLEMENTED,
)
def color_search():
return "Not implemented"


@app.get(
"/text_search/{text}",
summary="Search images by text",
status_code=status.HTTP_501_NOT_IMPLEMENTED,
)
def text_search():
return "Not implemented"


@app.get(
"/image_search/",
summary="Search images by another image",
status_code=status.HTTP_501_NOT_IMPLEMENTED,
)
def image_search():
return "Not implemented"


@app.get("/", summary="Hello, world")
def hello():
return "Hello, world!"
6 changes: 4 additions & 2 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ services:
container_name: backend
build: backend
ports:
- "8001:8000"
- "8000:8000"
environment:
- SCRAPER_URL=http://scraper:8000
volumes:
- ./config:/app/config
- ./backend/src:/app/src
scraper:
container_name: scraper
build: scraper
ports:
- "8000:8000"
- "8001:8000"
volumes:
- ./config:/app/config
- ./scraper/src:/app/src
Expand Down
11 changes: 11 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
package-lock.json
7 changes: 7 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# isat-cv-frontend

## Usage
```bash
npm install
npm run build -- --open
```
22 changes: 22 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "frontend",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^1.0.0-next.90",
"@sveltejs/kit": "^1.0.0-next.587",
"svelte": "^3.54.0",
"svelte-check": "^2.9.2",
"tslib": "^2.4.1",
"typescript": "^4.9.3",
"vite": "^4.0.0"
},
"type": "module"
}
2 changes: 2 additions & 0 deletions frontend/src/app.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
declare namespace App {
}
12 changes: 12 additions & 0 deletions frontend/src/app.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
92 changes: 92 additions & 0 deletions frontend/src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<!-- src/routes/+page.svelte -->
<script context="module">
export const BACKEND_URL = 'http://0.0.0.0:8000';
</script>

<script>
let isLoading = false;
let startPage = '';
let amount = '';

const handleButtonClick = async () => {
if (!startPage || !amount) {
alert('Please fill in all fields.');
return;
}

isLoading = true;
try {
const url = `${BACKEND_URL}/scrape/${startPage}/${amount}`;
const response = await fetch(url, { method: 'POST' });
} catch (error) {
console.error('Error:', error);
} finally {
isLoading = false;
}
};
</script>

<main>
<h1>Educational Project</h1>
<h1>Scraper</h1>
<h3>Fill in start page and amount of images to be scraped, then click on "Scrape" button</h3>
<div class="input-group">
<input type="text" id="startPage" bind:value={startPage} placeholder="Enter start page" />
<input type="number" id="amount" bind:value={amount} placeholder="Enter amount" />
</div>
<button on:click={handleButtonClick} disabled={isLoading}>
{isLoading ? 'Loading...' : 'Scrape'}
</button>
</main>

<style>
main {
text-align: center;
padding: 1.5em;
max-width: 360px;
margin: 0 auto;
}

h1 {
color: #3498db;
font-size: 2em;
font-weight: 700;
margin-bottom: 15px;
}

.input-group {
display: flex;
justify-content: space-between;
margin-bottom: 15px;
text-align: left;
}

.input-group input {
padding: 8px;
margin-bottom: 8px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 0.9em;
}

button {
background-color: #3498db;
color: white;
padding: 10px 20px;
font-size: 1em;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}

button:disabled {
background-color: #ccc;
cursor: not-allowed;
}

button:hover:enabled {
background-color: #217dbb;
}
</style>
Binary file added frontend/static/favicon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions frontend/svelte.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),

kit: {
adapter: adapter()
}
};

export default config;
13 changes: 13 additions & 0 deletions frontend/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
}
8 changes: 8 additions & 0 deletions frontend/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()]
};

export default config;
11 changes: 10 additions & 1 deletion scraper/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ async def lifespan(_: FastAPI):

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_origins=[
"http://localhost:8000",
"http://127.0.0.1:8000",
"http://0.0.0.0:8000",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
Expand Down Expand Up @@ -57,3 +61,8 @@ async def scrape(page: int, amount: int) -> None:
detail=f"Failed to scrape images from page {info.page}",
)
logger.info(f"Scraped {amount} images")


@app.get("/", summary="Check availability")
async def hello():
return "Scraper is running!"
Loading