Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Check out, review, and merge locally
- Step 1. Fetch and check out the branch for this merge request
- git fetch origin
- git checkout -b "prod" "origin/prod"
- Step 2. Review the changes locally
- Step 3. Merge the branch and fix any conflicts that come up
- git fetch origin
- git checkout "master"
- git merge --no-ff "prod"
- Step 4. Push the result of the merge to GitLab
- git push origin "master"
- Tip: You can also checkout merge requests locally by following these guidelines
- */
- /* tslint: disable */
- import * as XLSX from "xlsx";
- import React, { useState } from "react";
- import axios from "axios";
- export default function FileUpload(props) {
- const [selectedExcel, setSelectedExcel] = useState<File | null>(null);
- const [jsonForExcel, setJsonForExcel] = useState([]);
- const [excelUploadPostResponse, setExcelUploadPostResponse] = useState([]);
- const [existingFileCount, setExistingFileCount] = useState(0);
- const [jsonForCsv, setJsonForCsv] = useState([]);
- function excelUpload( event ) {
- const selectedExcel = event.target.files[0]
- setSelectedExcel(selectedExcel);
- console.log(selectedExcel);
- setExcelUploadPostResponse([]);
- const fileReader = new FileReader();
- fileReader.readAsBinaryString(selectedExcel as Blob);
- fileReader.onload = () => {
- const binaryExcel = fileReader.result;
- console.log("binaryExcel", binaryExcel);
- const workbook = XLSX.read(binaryExcel, { type: "binary" });
- console.log("workbook", workbook);
- if (workbook.SheetNames.length === 1) {
- const data = XLSX.utils.sheet_to_json(
- workbook.Sheets[workbook.SheetNames[0]]
- );
- setJsonForExcel(data);
- console.log(data);
- } else {
- const data = XLSX.utils.sheet_to_json(
- workbook.Sheets["Output (2)"]
- );
- setJsonForExcel(data);
- console.log(data);
- }
- };
- if (event && event.target && event.target.value) {
- event.target.value = "";
- }
- }
- function clearUpload(): void {
- setSelectedExcel(null);
- setJsonForExcel([]);
- }
- function triggerUpload(): void {
- if (jsonForExcel.length) {
- setExcelUploadPostResponse([]);
- postExcel();
- }
- }
- async function postExcel(): Promise<void> {
- try {
- const uploadResponse = await axios.post(
- "https://google.com/v1/excel_upload",
- jsonForExcel
- );
- if (uploadResponse && uploadResponse.data && uploadResponse.data.length > 0) {
- setExcelUploadPostResponse(uploadResponse.data);
- uploadResponse.data.forEach((element) => {
- if (element.Message) {
- setExistingFileCount(
- (prevFileCount) => prevFileCount + 1
- );
- }
- });
- } else {
- }
- // setLoading(false);
- } catch (e) {
- // setLoading(false);
- // throw new Error("There was an error on user authentication");
- }
- }
- const openFile = function(event) {
- let input = event.target;
- let reader = new FileReader();
- reader.onload = function() {
- let text = reader.result;
- console.log(text);
- const lines = text.split("\n");
- console.log(lines);
- let csvData = [];
- for (let count = 0; count < lines.length; count++) {
- const rowContent = lines[count].split(",");
- console.log(rowContent);
- csvData.push(rowContent);
- }
- console.log(csvData);
- setJsonForCsv(csvData);
- };
- reader.readAsText(input.files[0]);
- }
- return (
- <>
- <input
- type="file"
- id="fileInput"
- className="drop-zoon__file-input"
- accept=".xls,.xlsx"
- onChange={excelUpload}
- />
- <button
- onClick={triggerUpload}
- id="triggerUpload"
- >
- Trigger Build
- </button>
- <button
- aria-label="delete"
- style={{ height: "40px" }}
- onClick={clearUpload}
- >
- Clear
- </button>
- <div>
- <br />
- {excelUploadPostResponse.map((files) => {
- if (!files.hasOwnProperty("Error"))
- return (
- <div>
- {files.hasOwnProperty("file") && (
- <div>
- {`File Name: `} <b>{`${files.file}`}</b>
- </div>
- )}
- <br />
- </div>
- );
- return <></>;
- })}
- </div>
- {jsonForExcel && (
- <>
- <table
- aria-label="simple table"
- style={{
- boxShadow:
- "0px 2px 1px -1px rgb(0 0 0 / 20%), 0px 1px 1px 0px rgb(0 0 0 / 14%), 0px 1px 3px 0px rgb(0 0 0 / 12%)",
- borderRadius: "5px",
- }}
- >
- <thead>
- <tr
- style={{
- background: "#edf5f3",
- }}
- >
- {jsonForExcel &&
- jsonForExcel.length > 0 &&
- Object.keys(jsonForExcel[0]).map(
- (row) => <th key={row}>{row}</th>
- )}
- </tr>
- </thead>
- <tbody>
- {jsonForExcel &&
- jsonForExcel.length > 0 &&
- jsonForExcel.map((row, index) => (
- <tr key={`tablerow${index}`}>
- {Object.keys(row).map((key, index) => (
- <td
- scope="row"
- key={`${row[key]}trow${index}`}
- >
- {row[key]}
- </td>
- ))}
- </tr>
- ))}
- </tbody>
- </table>
- <br />
- <br />
- <br />
- <br />
- <br />
- </>
- )}
- <input type='file' accept='.csv' onChange={(event) => openFile(event)} />
- {jsonForCsv && (
- <>
- <table
- aria-label="simple table"
- style={{
- boxShadow:
- "0px 2px 1px -1px rgb(0 0 0 / 20%), 0px 1px 1px 0px rgb(0 0 0 / 14%), 0px 1px 3px 0px rgb(0 0 0 / 12%)",
- borderRadius: "5px",
- }}
- >
- {/* <thead>
- <tr
- style={{
- background: "#edf5f3",
- }}
- >
- {jsonForCsv &&
- jsonForCsv.length > 0 &&
- jsonForCsv[0].map(
- (row) => <th key={row}>{row}</th>
- )}
- </tr>
- </thead> */}
- <tbody>
- {jsonForCsv &&
- jsonForCsv.length > 0 &&
- jsonForCsv.map((row, index) => (
- <tr key={`tablerow${index}`}>
- {row.map((key, index) => (
- <td
- scope="row"
- key={`${row[key]}trow${index}`}
- >
- {key}
- </td>
- ))}
- </tr>
- ))}
- </tbody>
- </table>
- <br />
- <br />
- <br />
- <br />
- <br />
- </>
- )}
- </>
- );
- }
- /*
- how to identify a face in uploaded image and replace with a smiley in react
- To identify a face in an uploaded image and replace it with a smiley in a React application, you can use a combination of facial detection libraries like Face API or OpenCV.js for face detection and canvas manipulation to overlay the smiley.
- Here’s a step-by-step guide:
- Steps:
- Install Dependencies: Use a face detection library such as face-api.js:
- npm install face-api.js
- Setup File Upload and Image Rendering: Allow users to upload an image and render it on a <canvas>.
- Detect Faces in the Image: Use face-api.js to detect faces in the uploaded image.
- Overlay Smiley: Draw smiley faces on top of the detected face regions using the <canvas> API.
- Example Code tsx:
- */
- import React, { useRef, useState } from "react";
- import * as faceapi from "face-api.js";
- const FaceToSmiley = () => {
- const [loading, setLoading] = useState(false);
- const fileInputRef = useRef<HTMLInputElement | null>(null);
- const canvasRef = useRef<HTMLCanvasElement | null>(null);
- const imgRef = useRef<HTMLImageElement | null>(null);
- // Load models when the component mounts
- React.useEffect(() => {
- const loadModels = async () => {
- setLoading(true);
- await faceapi.nets.ssdMobilenetv1.loadFromUri("/models"); // Path to models folder
- await faceapi.nets.faceLandmark68Net.loadFromUri("/models");
- setLoading(false);
- };
- loadModels();
- }, []);
- const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (file && imgRef.current) {
- imgRef.current.src = URL.createObjectURL(file);
- }
- };
- const handleImageLoaded = async () => {
- if (!imgRef.current || !canvasRef.current) return;
- const img = imgRef.current;
- const canvas = canvasRef.current;
- // Detect faces in the image
- const detections = await faceapi.detectAllFaces(img);
- // Set canvas size to match the image
- canvas.width = img.width;
- canvas.height = img.height;
- // Draw the image on the canvas
- const ctx = canvas.getContext("2d");
- if (ctx) {
- ctx.drawImage(img, 0, 0, img.width, img.height);
- // Replace each detected face with a smiley
- detections.forEach((detection) => {
- const box = detection.box;
- const smiley = "😊";
- // Draw smiley over detected face region
- ctx.font = `${box.width}px Arial`;
- ctx.textAlign = "center";
- ctx.textBaseline = "middle";
- ctx.fillText(smiley, box.x + box.width / 2, box.y + box.height / 2);
- });
- }
- };
- return (
- <div>
- {loading && <p>Loading face detection models...</p>}
- <input
- type="file"
- accept="image/*"
- ref={fileInputRef}
- onChange={handleFileUpload}
- />
- <div style={{ position: "relative" }}>
- <img
- ref={imgRef}
- onLoad={handleImageLoaded}
- alt="uploaded"
- style={{ display: "none" }}
- />
- <canvas ref={canvasRef} />
- </div>
- </div>
- );
- };
- export default FaceToSmiley;
- /*
- Explanation:
- Face API Models:
- The example uses face-api.js for face detection.
- The models are loaded from the /models directory (you can download them here).
- File Upload:
- Users upload an image via an <input> element.
- The image is loaded into an invisible <img> element for processing.
- Canvas Rendering:
- The image is drawn on a <canvas> element for manipulation.
- The smiley is drawn at each detected face's coordinates using the fillText method.
- Overlay Smiley:
- Each detected face's bounding box is replaced by a smiley using the bounding box dimensions to set the smiley's size and position.
- Additional Notes:
- Model Path: Ensure the /models folder is accessible in your public directory. It should contain the .bin files for face-api.js.
- Improvement Ideas:
- Allow resizing of smileys for better fit.
- Add multiple smiley options for fun customization.
- Include error handling for when no faces are detected.
- With this implementation, users can upload an image, and all faces will be replaced with smileys dynamically!
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement