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

Aric/producthunt pink hairs #2

Open
wants to merge 6 commits into
base: eliot/with-backend
Choose a base branch
from
Open
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
23 changes: 22 additions & 1 deletion backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from flask_cors import CORS
import uuid
from flask import send_from_directory
import time
import os

model = keras.models.load_model('multi-keras.h5')

Expand Down Expand Up @@ -58,6 +60,16 @@ def send_js(path):
return send_from_directory('images', path)


@app.route('/recent_images')
def view_recent_images():
"""
Endpoints returning recently uploaded images from the community
"""
paths = get_most_recent_photos()

return jsonify({'paths': paths}), 200


def readb64(encoded_data):
nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
Expand All @@ -78,11 +90,20 @@ def process_upload(data):
combined, _ = add_pink_hair(img)

combined = (combined * 255.0).astype(np.uint8)
path = 'images/{}.jpg'.format(uuid.uuid4())
# We are using the timestamp ms as a sorting key to show the post recent
# pictures taken to our frontend, and we use a uuid4 as a unique identifier
path = 'images/{}{}.jpg'.format(time.time(), uuid.uuid4())
cv2.imwrite(path, combined)

return jsonify({'path': '/' + path})


def get_most_recent_photos(directory='images', count=10):
files = [os.path.join(directory, f) for f in os.listdir('images') if os.path.isfile(os.path.join('images', f))]
files.sort(reverse=True)
return files[0:count]



graph = None
graph = tf.get_default_graph()
Expand Down
14 changes: 12 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,28 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"@mui/material": "^5.2.5",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"add": "^2.0.6",
"blueimp-load-image": "^5.16.0",
"install": "^0.13.0",
"npm": "^8.3.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-html5-camera-photo": "^1.5.5",
"react-medium-image-zoom": "^4.3.5",
"react-scripts": "4.0.3",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1"
"web-vitals": "^1.0.1",
"yarn": "^1.22.17"
},
"scripts": {
"start": "react-scripts start",
Expand All @@ -42,6 +51,7 @@
]
},
"devDependencies": {
"@types/blueimp-load-image": "^5.14.4"
"@types/blueimp-load-image": "^5.14.4",
"@types/react-html5-camera-photo": "^1.5.1"
}
}
8 changes: 8 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
Expand Down
2 changes: 1 addition & 1 deletion src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
display: flex;
align-content: center;
justify-content: center;
height: 100vh;
height: 10vh;
}

.file-input {
Expand Down
175 changes: 130 additions & 45 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,89 @@
import React, { ChangeEvent, useState } from 'react';
import React, { ChangeEvent, useEffect, useState } from 'react';
import './App.css';
import AddButton from './components/AddButton';
import RecentImages from './components/RecentImages';
import loadImage, { LoadImageResult } from 'blueimp-load-image';
import { API_URL } from './Constants';
import CameraView from './components/CameraView';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';


import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Camera from 'react-html5-camera-photo';

// Got that as a view wrapper to center elements
// from the MUI docuementation.
// Sorry but in three hours, that's what you get :)
const Item = styled(Paper)(({ theme }) => ({
...theme.typography.body2,
padding: theme.spacing(1),
textAlign: 'center',
color: theme.palette.text.secondary,
}));

function App() {
const [result, setResult] = useState<string | null>(null)

let uploadImageToServer = (file: File) => {
const [cameraModeEnabled, setCameraModeEnabled] = useState<boolean>(false)
const [recentImages, setRecentImages] = useState<string[]>([])

// Fetch recently uploaded images from the community
let getRecentImages = async () => {
const response = await fetch(API_URL + '/recent_images', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});

if (response.status !== 200) {
throw new Error("Bad response from server");
}
const data = await response.json();
setRecentImages(data.paths);
}


useEffect(() => {
// Fetch recent images on mount
(async function () {
getRecentImages()
})()


}, []);

// Upload an base64 image string to the server and return the unserialized
// json response.
const uploadImageToServer = async (imageBase64: string) => {
let data = {
b64_img: imageBase64,

}

const response = await fetch(API_URL + '/upload', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(data)
});

if (response.status >= 400 && response.status < 600) {
throw new Error("Bad response from server");
}

return response.json();

}

// Take a selected image from the disk (<input type=file/>) and upload it to the server.
// Then update the recent images list state.
let onImageSelectedFromDisk = (file: File) => {
loadImage(
file,
{
Expand All @@ -16,52 +92,61 @@ function App() {
canvas: true
})
.then(async (imageData: LoadImageResult) => {

let image = imageData.image as HTMLCanvasElement

let imageBase64 = image.toDataURL("image/png")
let data = {
b64_img: imageBase64,
}
const response = await fetch(API_URL + '/upload', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(data)
});

if (response.status >= 400 && response.status < 600) {
throw new Error("Bad response from server");
}

const result = await response.json();
const imagePath = API_URL + result.path
setResult(imagePath)
await uploadImageToServer(imageBase64)
await getRecentImages()
})

.catch(error => {
console.error(error)
})
}

let onImageAdd = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
onImageSelectedFromDisk(e.target.files[0])
} else {
console.error("No file was picked")
}

let onImageAdd = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
uploadImageToServer(e.target.files[0])
} else {
console.error("No file was picked")
}
}

}

// Callback function for selfie shot using the user's camera.
// The image is uploaded to the server and the recent images list is updated.
const handleTakePhoto = async(imageBase64: string) => {
await uploadImageToServer(imageBase64)
await getRecentImages()
setCameraModeEnabled(false)
}


if (cameraModeEnabled === true) {
return <CameraView onPictureTaken={handleTakePhoto} />
} else {

// It's been a long time I did not touch a grid system so here is the best I could do
// in a few minutes.
return (
<div className="App">
<header className="App-header">
{!result && <AddButton onImageAdd={onImageAdd}/>}
{result && <img src={result} width={300} alt="result from the API"/>}
</header>
</div>
);
}

export default App;

<Grid container spacing={2}>
<Grid item xs={12}>
<Item>
<h1>Welcome to Photoroom Hair Styler</h1>
<Stack direction="row" justifyContent="center">
<Button variant="contained" onClick={() => {
setCameraModeEnabled(true)
}}>Take a selfie</Button>
<AddButton onImageAdd={onImageAdd}/>
</Stack>
<Stack direction="row" justifyContent="center">
<RecentImages images={recentImages} API_URL={API_URL} />
</Stack>
</Item>
</Grid>
</Grid>
);
}
}

export default App;
20 changes: 20 additions & 0 deletions src/components/CameraView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import Camera from 'react-html5-camera-photo';
import 'react-html5-camera-photo/build/css/index.css';



export default function CameraView ({
onPictureTaken,
}: {
onPictureTaken: (imageData: string) => void;
}): JSX.Element {

return (
<div>
<Camera
onTakePhoto = { (dataUri: string) => { onPictureTaken(dataUri); return ; } }
/>)
</div>


)}
35 changes: 35 additions & 0 deletions src/components/RecentImages.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from "react";
import ImageList from '@mui/material/ImageList';
import ImageListItem from '@mui/material/ImageListItem';
import Zoom from 'react-medium-image-zoom'
import 'react-medium-image-zoom/dist/styles.css'



export default function RecentImages ({
images,
API_URL
}: {
images: string[],
API_URL: string
}): JSX.Element {

return (
<ImageList sx={{ width: 500, height: 450 }} cols={3} rowHeight={164}>
{images.map((img_url) => (
<Zoom>
<ImageListItem key={img_url}>

<img
src={`${API_URL+"/"+img_url}`}
srcSet={`${API_URL+"/"+img_url}`}
alt={img_url}
loading="lazy"
/>
</ImageListItem>
</Zoom>
))}
</ImageList>


)}
Loading