I have added the face detection API from Clarifai APi to my project, however, whenever i copy an image to my project and click on detects, it actually shows the image but it is not detecting the face.
see below App.js and FaceRecognition.js
import React, {Component} from 'react';
import Clarifai from 'clarifai';
import Navigation from './components/Navigation/Navigation';
import Logo from './components/Logo/Logo';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import Rank from './components/Rank/Rank';
import './App.css';
const app = new Clarifai.App({
apiKey: 'xxxxxxxxxxxx'
});
class App extends Component {
constructor() {
super();
this.state = {
input: '',
imageUrl: '',
box: {}
}
}
calculateFaceLocation =(data) => {
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - (clarifaiFace.right_col * width),
bottomRow: height - (clarifaiFace.bottom_row * height)
}
}
displayFaceBox = (box) => {
console.log(box)
this.setState({box: box});
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(
Clarifai.FACE_DETECT_MODEL,
this.state.input)
.then( response => this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log(err));
}
render() {
return (
<div className="App">
<Navigation />
<Logo />
<Rank />
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit} />
<FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
</div>
);
}
}
export default App;
FaceRecognition.js
import React from 'react';
import './FaceRecognition.css';
const FaceRecognition = ({imageUrl, box}) => {
return (
<div className='center ma'>
<div className='absolute mt2'>
<img id='inputimage' alt='' src={imageUrl} width='500px' height='auto' />
<div className='bounding-box' style=
{{top: box.topRow, right: box.rightCol, bottom: box.bottomRow, left: box.leftCol}}></div>
</div>
</div>
);
}
export default FaceRecognition;
FaceRecognition.css
bounding-box {
position: absolute;
box-shadow: 0 0 0 3px #149df2 inset;
display: flex;
flex-wrap: wrap;
justify-content: center;
cursor: pointer;
}
what am i doing wrong?
i tried copy paste from the actual Clarifai API code, but no luck
the bounding-box css is not even showing up in the console.
please help me
First of all, please don't use this client: https://github.com/Clarifai/clarifai-javascript, it has been deprecated for a while and several things in this package are very old and broken.
If you're purely developing client-side, you can use the REST endpoints directly: https://docs.clarifai.com/api-guide/predict/images (see "Javascript (REST)" snippets throughout the docs)
I also recommend to use PAT instead of API keys. This will allow you access across all your Clarifai apps with a single token.
Clarifai has changed the way to use their Api. On Clarifai Face detect model , click to use model, then you can copy the code on how to use their Api.
https://clarifai.com/clarifai/main/models/face-detection?utm_source=clarifai&utm_medium=referral&tab=versions
Then you can import your PAT and other credentials requested for in the code from Clarifai portal.
Use this as a guide https://help.clarifai.com/hc/en-us/articles/4408131744407-Integrating-Clarifai-in-your-React-Javascript-project
You are welcome 🤗
Related
I would like to center the selected image instead of having it showing on the left hand side.
See image of behaviour:
I'm using the packages from the sandbox below in Next.js 11 with TailwindCSS 2.2.4:
https://codesandbox.io/s/5vn3lvz2n4
Dependencies:
"react-images": "^1.2.0-beta.7",
"react-photo-gallery": "^8.0.0"
I'm having a hard time targeting the CSS class, but I narrowed down to:
class="react-images__view react-images__view--isModal css-1qrom1v css-1ycyyax" using the browser dev tool in Safari.
Below is my PhotoLibrary file:
import React, { useState, useCallback } from "react";
import Gallery from "react-photo-gallery";
import Carousel, { Modal, ModalGateway } from "react-images";
import { photos } from "../data/photoData";
export default function PhotoLibrary() {
const [currentImage, setCurrentImage] = useState(0);
const [viewerIsOpen, setViewerIsOpen] = useState(false);
const openLightbox = useCallback((event, { photo, index }) => {
setCurrentImage(index);
setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
setCurrentImage(0);
setViewerIsOpen(false);
};
return (
<div>
<Gallery photos={photos} onClick={openLightbox} />
<ModalGateway>
{viewerIsOpen ? (
<Modal onClose={closeLightbox}>
<Carousel
currentIndex={currentImage}
views={photos.map((x) => ({
...x,
srcset: x.srcSet,
caption: x.title,
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
Has anyone played around with the carousel in Next.js and able to see what I'm doing wrong? If you have a better solution I'm open to that too.
Add the following CSS to your globals.css file.
.react-images__view-image--isModal {
display: inline-block;
left: 50%
}
i am trying to make a theme system on a react project that uses redux with a reducer that manages themes according to the user's local storage. But here my problem is that I used css files to define my styles on all of my components. However, I have all my logic with 2 javascript objects for light or dark mode. So I can't use js in css files unless I use css variables but I don't know how.
Here is my structure :
In my app.js I imported useSelector and useDispatch from react redux to access the global state :
import React from 'react';
import './App.css';
import Footer from './components/Footer';
import Header from './components/Header';
import Presentation from './components/Presentation';
import Projects from './components/Projects';
import Skills from './components/Skills';
import Timeline from './components/Timeline';
import { switchTheme } from './redux/themeActions';
import { useSelector, useDispatch } from 'react-redux';
import { lightTheme, darkTheme } from './redux/Themes';
function App() {
const theme = useSelector(state => state.themeReducer.theme);
const dispatch = useDispatch();
return (
<div className="App">
<Header />
<input type='checkbox' checked={theme.mode === 'light' ? true : false}
onChange={
() => {
if(theme.mode === 'light') {
dispatch(switchTheme(darkTheme))
} else {
dispatch(switchTheme(lightTheme))
}
}} />
<div className="top">
<div className="leftPart">
<Presentation />
<Skills />
</div>
<Timeline />
</div>
<Projects />
<Footer />
</div>
);
}
export default App;
and in themes.js I have my 2 objects which represent the themes :
export const darkTheme = {
mode: 'dark',
PRIMARY_BACKGROUND_COLOR: '#171933',
SECONDARY_BACKGROUND_COLOR: '#1e2144',
TERTIARY_BACKGROUND_COLOR: '#0a0c29',
PRIMARY_TEXT_COLOR: '#eee',
SECONDARY_TEXT_COLOR: '#ccc',
PRIMARY_BORDER_COLOR: '#aaa'
}
export const lightTheme = {
mode: 'light',
PRIMARY_BACKGROUND_COLOR: '#D3CEC8',
SECONDARY_BACKGROUND_COLOR: '#E5DFD9',
TERTIARY_BACKGROUND_COLOR: '#C1BFBC',
PRIMARY_TEXT_COLOR: '#222',
SECONDARY_TEXT_COLOR: '#333',
PRIMARY_BORDER_COLOR: '#555'
}
You can make use of data attributes.
I have done the same in one my project like so :-
[data-color-mode="light"] {
--color-focus-ring: #7daee2;
--color-link-hover: #0039bd;
--color-primary-bg: #eef6ff;
--color-primary-text: #212121;
--color-primary-border: #98b2c9;
--color-secondary-bg: #c3d7f0;
--color-secondary-text: #1a1a1a;
}
[data-color-mode="dark"] {
--color-focus-ring: #5355d4;
--color-link-hover: #4183c4;
--color-primary-bg: #080808;
--color-primary-text: #f1f1f1;
--color-primary-border: #525252;
--color-secondary-bg: #191919;
--color-secondary-text: #d8d5d5;
}
You can add the attribute to your top-level element (assuming div) like so:-
<div className="appContainer" data-color-mode="light" ref={appRef}> ></div>
Now use that appRef to change the data-color-mode attribute as well update the localstorage in one function. Updating the data-color-mode allows you to toggle between css variable colors easily. In my code, I have done this the following way:-
const toggleColorMode = () => {
const nextMode = mode === "light" ? "dark" : "light";
// container is appRef.current only
container?.setAttribute("data-color-mode", nextMode);
setMode(nextMode);
};
I am not using redux for this. Simply React Context API is being used by me but it's doable in your scenario as well.
You can take more reference from the repo - https://github.com/lapstjup/animeccha/tree/main/src
Note - I think there are other routes where people go with CSS-IN-JS but I haven't explored them yet. This solution is one of the pure css ways.
Fun fact - Github has implemented their newest dark mode in a similar way and that's where I got the idea as well. You can inspect their page to see the same attribute name :D.
im using an old version of a CRUD so i think that some codes aren't working any more, but vscode is not point it like an error, so the page goes on but my content box still empty. could somone help me?
these are 4 codes that i think that should be improved...
first my header that dont show me the props.icon tasks
import './Header.css'
import React from 'react'
export default function props () {
return (
<header className = "header d-none d-sm-flex flex-column">
<h1 className="mt-3">
<i className={`fa fa-${props.icon}`}></i>{props.title}
</h1>
<p className="lead text-muted">{props.subtitle}</p>
</header>
)}
here my main.jsx which my header goes inside by import
import './Main.css'
import React from 'react'
import Header from './Header'
function props () {
return (
<React.Fragment>
<Header {...props}/>
<main className="content container-fluid">
<div className="p-3 mt-3">
{props.children}
</div>
</main>
</React.Fragment>
)
}
export default props
now my app.jsx and app.css wht render my Htmls
import 'bootstrap/dist/css/bootstrap.min.css'
import 'font-awesome/css/font-awesome.min.css'
import './App.css'
import React from 'react'
import {HashRouter} from 'react-router-dom'
import Routes from './Routes'
// import Home from '../components/home/Home'
import Logo from '../components/template/Logo'
import Navi from '../components/template/Navi'
import Footer from '../components/template/Footer'
// import props from '../../../frontend2/src/components/template/main'
function Props () {
return(
<HashRouter>
<div className="App">
<Logo />
<Navi/>
<Routes/>
<Footer />
</div>
</HashRouter>
)
}
export default Props
//////////////////////////
:root{
--bg-dark: #1a2f3a;
--logo-height: 100px;
--header-height: 100px;
--aside-width: 225px;
--footer-height: 40px;
--shadow:
0 2px 23px 0 rgba(0, 0, 0, 0.1)
0 2px 49px 0 rgba(0, 0, 0, 0.06)
}
*{
box-sizing: border-box;
font-family: 'Montserrat', sans-serif;
}
/* layout em grid */
.App {
margin: 0px;
display: grid;
grid-template-columns: var(--aside-width) 1fr;
grid-template-rows:
var(--header-height)
1fr
var(--footer-height);
grid-template-areas:
"logo header"
"menu content"
"menu footer";
height: 100vh;
background-color: #f5f5f5;
}
aside.logo{
grid-area: logo;
}
header.header{
grid-area: header;
}
aside.menu-area{
grid-area: menu;
}
main.content{
grid-area: content;
}
footer.footer{
grid-area: footer;
}
then my routes.jsx
import React from 'react'
import {Switch, Route, Redirect} from 'react-router'
import Home from '../components/home/Home'
import UserCrud from '../components/user/UserCrud'
function Props (){
return(
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/users" component={UserCrud}/>
<Redirect from="*" to="/"/>
</Switch>
)
}
export default Props
and finally but not less important my home which own my main and is my / path
import React from 'react'
import {Switch, Route, Redirect} from 'react-router'
import Home from '../components/home/Home'
import UserCrud from '../components/user/UserCrud'
function Props (){
return(
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/users" component={UserCrud}/>
<Redirect from="*" to="/"/>
</Switch>
)
}
export default Props
please help me out here, im stucked search this error by 2 days now, im prety sure that i got a sintax error, if u got this expertise please share
here are some issues from the console but i dont even know from where came this history one, pleasee...
Warning: Please use require("history").createMemoryHistory instead of require("history/createMemoryHistory"). Support for the latter will be removed in the next major release.
stack_frame_overlay_proxy_console # index.js:2178
index.js:2178 Warning: Please use require("history").PathUtils instead of require("history/PathUtils"). Support for the latter will be removed in the next major release.
stack_frame_overlay_proxy_console # index.js:2178
react-dom.development.js:88 Warning: componentWillMount has been renamed, and is not recommended for use. See react-unsafe-component-lifecycles for details.
Move code with side effects to componentDidMount, and set initial state in the constructor.
Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.
Please update the following components: HashRouter, Route, Router, Switchnull
I think you might have got a bit mixed up regarding the nature of props in the React framework. Consider reading over the documentation to get more of an overview of how we use them to structure data flow in React applications.
To put it briefly, props are the inputs that components pass to one another in order to populate the UI and update the state of an application. In functional React, we can think of them as the parameters that a function (i.e. component) takes in order to return a given output in JSX.
So when it comes to your code, naming all your component functions Props is not the same as them actually having props available to use. First, a component's parent has to pass it a prop inside the JSX, and then it has to access that prop from the function parameters before it can be used. Here is a simplified example below which will hopefully make the pattern more clear for you:
// App.jsx
function App() {
return (
<div>
<Header title={'someValue'}/>
<MainComponent />
</div>
);
};
// Header.jsx
function Header(props) {
return (
<header>
<h1>{props.title}</h1>
</header>
);
};
I see you were also trying to use props.children which is a slightly different feature and does not work in the same way. The children of a React component are any elements that that component wraps around in the instance that it is declared. The children themselves do not have to passed as props in the usual manner, but they must still be accessed from the function's parameters. In this example, the props.children of MainComponent is the div with the class child:
// App.jsx
function App() {
return (
<div>
<MainComponent>
<div class="child">
</div>
</MainComponent>
</div>
);
};
// MainComponent.jsx
function MainComponent(props) {
return (
<main>
{props.children}
</main>
);
};
I am trying to test CSS properties that i have defined inside a class in css, wing the react testing library. However I am unable to do so.
Adding the simplified snippets.
import React from "react";
import { render, screen } from "#testing-library/react";
import '#testing-library/jest-dom/extend-expect';
import styled from "styled-components";
const Title = styled.span`
display: none;
background: red;
`
test("testRender", () => {
render(
<div>
<Title>Test</Title>
</div>
)
const spanElement = screen.getByText("Test");
const elementStyle = window.getComputedStyle(spanElement);
expect(elementStyle.display).toBe('none');
});
The test fails at the expect statement. I have tried refactoring to traditional css, there also the test fails. In both cases, I have tested it manually and the styles are taking effect.
I also understand that we should not directly test CSS properties, but I have tried testing the visibility with toBeVisible(), but that only works if the display: none is directly entered as a style, and not as part of a class.
This should be a very simple thing, that works out of the box, but I have been at it for some time now, without any luck.
Any help is appreciated.
I agree with #ourmaninamsterdam answer.
In addition, for checking appearance or disappearance of any element, you can also use .not.toBeInTheDocument like so:
expect(screen.queryByText("Test")).not.toBeInTheDocument();
NOTE: You must use queryByText instead of getByText in this case since queryByText wont throw an error if it doesn't find the element (it will return null).
Official docs Reference - https://testing-library.com/docs/guide-disappearance#nottobeinthedocument
You can use expect(screen.getByText("Test")).not.toBeVisible();
import React from "react";
import { render, screen } from "#testing-library/react";
import "#testing-library/jest-dom/extend-expect";
import styled from "styled-components";
it("does display", () => {
const Title = styled.span`
display: block;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).toBeVisible();
});
it("doesn't display", () => {
const Title = styled.span`
display: none;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).not.toBeVisible();
});
...see the sandbox: https://codesandbox.io/s/blazing-river-l6rn6?file=/App.test.js
I am trying to set a background in Gatsby using gatsby-background-image plugin.
My query returns sourceUrl and alt-text just fine. However, when running gatsby develop it gives me an error "TypeError: Cannot read property 'hero' of undefined". Doing some research I think I might have to use ChildImageSharp to specify fluid. However, I am not really sure if that is possible for an ACF field?
import React from "react"
import BackgroundImage from "gatsby-background-image"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
const IndexPage = (props) => (
<Layout>
<SEO title="Home" />
<BackgroundImage
className="masthead"
fadeIn
fluid={props.data.wordpress.pages.nodes.undersideACFgraphql.hero.sourceUrl}
>
<div className="black-overlay">
<div className="content-box">
<h1>This is where my h1 tag goes</h1>
<h2>This is my sub head</h2>
</div>
</div>
</BackgroundImage>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
export default IndexPage
export const pageQuery = graphql`
query MyQuery {
wordpress {
pages {
nodes {
undersideACFgraphql {
hero {
sourceUrl
altText
}
}
}
}
}
}
`;