Spaces:
Runtime error
Runtime error
| import React, { useRef, useEffect, useState } from "react"; | |
| import { StyleSheet, View, Button, Alert } from "react-native"; | |
| import { Camera, useCameraDevices } from "react-native-vision-camera"; | |
| import * as ImageManipulator from "expo-image-manipulator"; | |
| const App = () => { | |
| const [hasPermission, setHasPermission] = useState(false); | |
| const [cameraType, setCameraType] = useState("back"); // Default to rear camera | |
| const camera = useRef(null); | |
| const devices = useCameraDevices(); | |
| const device = cameraType === "back" ? devices.back : devices.front; | |
| useEffect(() => { | |
| (async () => { | |
| const status = await Camera.requestCameraPermission(); | |
| setHasPermission(status === "authorized"); | |
| })(); | |
| }, []); | |
| const captureImage = async () => { | |
| if (!camera.current) return; | |
| try { | |
| const photo = await camera.current.takePhoto({ | |
| quality: 0.8, // Adjust quality as needed | |
| }); | |
| console.log("Captured Image Path:", photo.path); | |
| // Correct image orientation for the rear camera | |
| const fixedImage = await ImageManipulator.manipulateAsync( | |
| photo.path, | |
| [{ flip: cameraType === "back" ? ImageManipulator.FlipType.Horizontal : undefined }], // Flip for rear camera | |
| { compress: 1, format: ImageManipulator.SaveFormat.JPEG } | |
| ); | |
| console.log("Fixed Image Path:", fixedImage.uri); | |
| // Send the fixed image to the backend | |
| const formData = new FormData(); | |
| formData.append("file", { | |
| uri: fixedImage.uri, | |
| type: "image/jpeg", | |
| name: "photo.jpg", | |
| }); | |
| const response = await fetch("https://<your-gradio-backend-url>", { | |
| method: "POST", | |
| body: formData, | |
| }); | |
| const data = await response.json(); | |
| Alert.alert("OCR Result", data || "No text detected."); | |
| } catch (error) { | |
| console.error("Error capturing image:", error); | |
| Alert.alert("Error", "Failed to capture image. Please try again."); | |
| } | |
| }; | |
| if (!device || !hasPermission) return <View style={styles.container} />; | |
| return ( | |
| <View style={styles.container}> | |
| <Camera | |
| ref={camera} | |
| style={StyleSheet.absoluteFill} | |
| device={device} | |
| isActive={true} | |
| photo={true} | |
| /> | |
| <View style={styles.buttonContainer}> | |
| <Button | |
| title={`Switch to ${cameraType === "back" ? "Front" : "Rear"} Camera`} | |
| onPress={() => | |
| setCameraType((prev) => (prev === "back" ? "front" : "back")) | |
| } | |
| /> | |
| <Button title="Capture Image" onPress={captureImage} /> | |
| </View> | |
| </View> | |
| ); | |
| }; | |
| const styles = StyleSheet.create({ | |
| container: { | |
| flex: 1, | |
| }, | |
| buttonContainer: { | |
| position: "absolute", | |
| bottom: 20, | |
| width: "100%", | |
| flexDirection: "row", | |
| justifyContent: "space-evenly", | |
| }, | |
| }); | |
| export default App; | |