feat: basic api complete

basic grid layout
This commit is contained in:
Mike 2024-07-17 22:23:47 -04:00
parent 85c989ce35
commit 721ed4fa4f
16 changed files with 444 additions and 15 deletions

164
.gitignore vendored
View file

@ -130,3 +130,167 @@ dist
.pnp.*
.DS_STORE
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
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/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# 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/

View file

View file

@ -0,0 +1,61 @@
from dotenv import load_dotenv
import google.generativeai as genai
import json
import os
from .photos import Pictures
from pydantic import BaseModel, HttpUrl
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
class Topics(BaseModel):
topic: str
class Results(BaseModel):
topic: str
medium_url: str
photo_id: int
photo_url: str
bad_match: bool
class AI:
genai = genai.configure(api_key=GEMINI_API_KEY)
def generate_topics(self) -> list:
model = genai.GenerativeModel(
"gemini-1.5-flash",
generation_config={
"response_mime_type": "application/json",
"response_schema": list[Topics],
},
)
prompt = """
Return 12 items for a toddler aged 2 to 3 to choose from in a memory game.
"""
response = model.generate_content(prompt).text
return json.loads(response)
def generate_card_json(self, photo_payload, topic):
prompt = f"""
This JSON payload will need to be analayzed. Your job is to pick the alt field with the best match for the toddler matching game. return the properties of the object
{photo_payload}
and the original topic is {topic}. If the alt text and topic are a bad match set the bad_match bool.
"""
model = genai.GenerativeModel(
"gemini-1.5-flash",
generation_config={
"response_mime_type": "application/json",
"response_schema": Results,
},
)
r = model.generate_content(prompt).text
return json.loads(r)

View file

@ -0,0 +1,53 @@
from .ai import AI
from .test_data import data
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import logging
import os
from .photos import Pictures
logger = logging.getLogger("uvicorn.error")
logger.setLevel(logging.DEBUG)
load_dotenv()
app = FastAPI()
ai = AI()
# IN HERE FOR LOCAL DEV
origins = ["http://localhost:5173"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
photos = Pictures(PEXELS_API_KEY)
@app.get("/")
async def read_main():
return data
# data = []
#
# topics = ai.generate_topics()
#
# try:
# for item in topics:
#
# logger.info(item)
# picture_data = photos.search(item["topic"])
#
# card_json = ai.generate_card_json(picture_data, item)
# logger.info(card_json)
#
# data.append(card_json)
#
# return data
# except Exception as e:
# logger.error(e)
# return {"error": "uname to handle request"}

View file

View file

@ -0,0 +1,20 @@
import requests
class Pictures:
def __init__(self, token) -> None:
self.url = "https://api.pexels.com"
self.parameters = {"orientation": "square", "size": "small"}
self.headers = {"Authorization": f"{token}"}
def search(self, topic):
search_path = "/v1/search"
search_params = {**self.parameters, "query": topic}
r = requests.get(
url=self.url + search_path, params=search_params, headers=self.headers
)
return r.json()

View file

@ -0,0 +1,35 @@
annotated-types==0.7.0
anyio==4.4.0
certifi==2024.6.2
click==8.1.7
dnspython==2.6.1
email_validator==2.2.0
fastapi==0.111.0
fastapi-cli==0.0.4
h11==0.14.0
httpcore==1.0.5
httptools==0.6.1
httpx==0.27.0
idna==3.7
Jinja2==3.1.4
markdown-it-py==3.0.0
MarkupSafe==2.1.5
mdurl==0.1.2
orjson==3.10.5
pydantic==2.7.4
pydantic_core==2.18.4
Pygments==2.18.0
python-dotenv==1.0.1
python-multipart==0.0.9
PyYAML==6.0.1
rich==13.7.1
shellingham==1.5.4
sniffio==1.3.1
starlette==0.37.2
typer==0.12.3
typing_extensions==4.12.2
ujson==5.10.0
uvicorn==0.30.1
uvloop==0.19.0
watchfiles==0.22.0
websockets==12.0

View file

@ -0,0 +1,74 @@
data = [
{
"medium_url": "https://images.pexels.com/photos/19314176/pexels-photo-19314176.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 19314176,
"photo_url": "https://www.pexels.com/photo/ball-in-golden-paper-19314176/",
"topic": "ball",
},
{
"medium_url": "https://images.pexels.com/photos/1592384/pexels-photo-1592384.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 1592384,
"photo_url": "https://www.pexels.com/photo/shallow-focus-photography-of-blue-alpine-car-1592384/",
"topic": "car",
},
{
"medium_url": "https://images.pexels.com/photos/444492/pexels-photo-444492.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 444492,
"photo_url": "https://www.pexels.com/photo/golden-retriever-puppy-mix-444492/",
"topic": "dog",
},
{
"medium_url": "https://images.pexels.com/photos/160722/cat-tiger-getiegert-feel-at-home-160722.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 160722,
"photo_url": "https://www.pexels.com/photo/silver-tabby-cat-lying-on-green-grass-160722/",
"topic": "cat",
},
{
"medium_url": "https://images.pexels.com/photos/694587/pexels-photo-694587.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 694587,
"photo_url": "https://www.pexels.com/photo/silhouette-of-boy-running-in-body-of-water-during-sunset-694587/",
"topic": "sun",
},
{
"medium_url": "https://images.pexels.com/photos/821718/pexels-photo-821718.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 821718,
"photo_url": "https://www.pexels.com/photo/full-moon-821718/",
"topic": "moon",
},
{
"medium_url": "https://images.pexels.com/photos/102104/pexels-photo-102104.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 102104,
"photo_url": "https://www.pexels.com/photo/red-and-orange-apple-fruit-102104/",
"topic": "apple",
},
{
"medium_url": "https://images.pexels.com/photos/2872767/pexels-photo-2872767.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 2872767,
"photo_url": "https://www.pexels.com/photo/photo-of-peeled-banana-on-yellow-plate-and-background-2872767/",
"topic": "banana",
},
{
"medium_url": "https://images.pexels.com/photos/207732/pexels-photo-207732.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 207732,
"photo_url": "https://www.pexels.com/photo/grayscale-photo-of-books-207732/",
"topic": "book",
},
{
"medium_url": "https://images.pexels.com/photos/1464625/pexels-photo-1464625.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 1464625,
"photo_url": "https://www.pexels.com/photo/grey-sneakers-with-dense-surface-of-texture-for-comfortable-everyday-wearing-1464625/",
"topic": "shoe",
},
{
"medium_url": "https://images.pexels.com/photos/2098848/pexels-photo-2098848.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 2098848,
"photo_url": "https://www.pexels.com/photo/brown-sun-hat-and-sandals-on-sand-2098848/",
"topic": "hat",
},
{
"medium_url": "https://images.pexels.com/photos/698275/pexels-photo-698275.jpeg?auto=compress&cs=tinysrgb&h=350",
"photo_id": 698275,
"photo_url": "https://www.pexels.com/photo/tree-surrounded-by-snow-698275/",
"topic": "tree",
},
]

View file

@ -1,11 +1,16 @@
import { useState } from "react";
import "./App.css";
import GameBoard from "./components/gameboard";
import Scoreboard from "./components/scoreboard";
function App() {
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
return (
<>
<GameBoard />
<Scoreboard score={score} highscore={highScore} />
<GameBoard score={score} setScore={setScore} />
</>
);
}

View file

@ -4,8 +4,8 @@ export default function Card(props) {
return (
<div
className="card"
onClick={(event) => onClick(event)}
data-cardName={props.title}
onClick={(event) => onClick(event, props.setScore, props.score)}
data-cardname={props.title}
>
<div className="card-img">
<Image src={props.imgSrc} alt={props.imgAlt} />
@ -19,7 +19,8 @@ function Image(props) {
return <img src={props.src} alt={props.alt} />;
}
function onClick(event) {
function onClick(event, setScore, score) {
// implement something to handle the things ID
setScore(score + 1);
console.log(event.currentTarget.dataset.cardname);
}

View file

@ -4,7 +4,6 @@ import "../styles/gameboard.css";
export default function GameBoard(props) {
const [cards, setCards] = useState([]);
useEffect(() => {
fetchCards({ setCards });
}, []);
@ -14,10 +13,12 @@ export default function GameBoard(props) {
{cards.map((item) => {
return (
<Card
title={item}
imgSrc="placeholder"
title={item.topic}
imgSrc={item.medium_url}
imgAl="Placeholder"
key={item}
key={item.topic}
setScore={props.setScore}
score={props.score}
/>
);
})}
@ -26,6 +27,6 @@ export default function GameBoard(props) {
}
async function fetchCards({ setCards }) {
// some async thing that loads the cards
setTimeout(() => setCards([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), 2000);
const cards = await fetch("http://localhost:8000/");
setCards(await cards.json());
}

View file

@ -0,0 +1,10 @@
import "../styles/scoreboard.css";
export default function Scoreboard(props) {
return (
<div className="scoreboard">
<p>SCORE: {props.score}</p>
<p>HIGH SCORE: {props.highscore}</p>
</div>
);
}

View file

@ -23,6 +23,7 @@ a:hover {
}
body {
padding: 0;
margin: 0;
display: flex;
place-items: center;

View file

@ -1,9 +1,8 @@
.card {
display: flex;
flex-direction: column;
min-width: 300px;
min-height: 300px;
background: gray;
padding: 1em;
}
.card-img img {

View file

@ -1,5 +1,7 @@
.gameboard {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 25px;
display: inline-grid;
/* grid-template-columns: 1fr 1fr 1fr; */
grid-template-columns: repeat(auto-fit, minmax(min(270px, 90%), 1fr));
gap: 1rem;
width: 75vw;
}

View file

@ -0,0 +1,3 @@
.scoreboard {
text-align: right;
}