In this post, we’ll walk through building a React Native app that generates children’s stories based on prompts and age ranges, using Hugging Face's powerful AI models. The app allows users to enter a prompt, select an age range, and then see a custom story along with a cartoonish image summarizing the story.
Let’s break down each part!
Start by creating a new React Native project with Expo:
npx create-expo-app@latest KidsStoryApp cd KidsStoryApp
Set up Expo Router in your app for easy navigation, and install any additional dependencies you may need, like icons or animations.
In the Home.js file, we set up a screen where users can select an age range, enter a story prompt, and press a button to generate a story.
import React, { useEffect, useRef, useState } from "react"; import { View, Text, TouchableOpacity, StyleSheet, TextInput, Animated, ActivityIndicator, } from "react-native"; import useKeyboardOffsetHeight from "../hooks/useKeyboardOffsetHeight"; import { HUGGING_FACE_KEY } from "../env"; import { useRouter } from "expo-router"; const Home = () => { const ageRanges = ["0-3", "4-6", "7-9"]; const [selectedAgeRange, setSelectedAgeRange] = useState("0-3"); const [textInput, setTextInput] = useState(""); const [isLoading, setIsLoading] = useState(false); const keyboardOffsetHeight = useKeyboardOffsetHeight(); const animatedValue = useRef(new Animated.Value(0)).current; const router = useRouter(); useEffect(() => { Animated.timing(animatedValue, { toValue: keyboardOffsetHeight ? -keyboardOffsetHeight * 0.5 : 0, duration: 500, useNativeDriver: true, }).start(); }, [keyboardOffsetHeight]); const handleAgeRangeSelect = (range) => setSelectedAgeRange(range); const handleShowResult = () => { if (textInput.length > 5) { fetchStory(); } else { alert("Please enter a bit more detail."); } }; async function fetchStory() { setIsLoading(true); try { let message = `Write a simple story for kids about ${textInput} ${ selectedAgeRange ? "for age group " selectedAgeRange : "" }, in plain words. Only provide the story content without any headings, titles, or extra information.`; const response = await fetch( "https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-3B-Instruct/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${HUGGING_FACE_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "meta-llama/Llama-3.2-3B-Instruct", messages: [{ role: "user", content: message }], max_tokens: 500, }), } ); if (!response.ok) throw new Error("Failed to fetch story"); const data = await response.json(); const storyContent = data.choices[0].message.content; // Summarize the story const summaryResponse = await fetch( "https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-3B-Instruct/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${HUGGING_FACE_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "meta-llama/Llama-3.2-3B-Instruct", messages: [ { role: "user", content: `Summarize this story in a line: "${storyContent}"` }, ], max_tokens: 30, }), }); if (!summaryResponse.ok) throw new Error("Failed to fetch summary"); const summaryData = await summaryResponse.json(); const summaryContent = summaryData.choices[0].message.content; router.push({ pathname: "/detail", params: { story: storyContent, summary: summaryContent }, }); } catch (error) { console.error("Error fetching story or summary:", error); alert("Error fetching story. Please try again."); } finally { setIsLoading(false); } } return ( <Animated.ScrollView bounces={false} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" > <h3> Key Components of Home.js </h3> <ul> <li> <strong>Text Input and Age Selector</strong>: Allows the user to select an age range and enter a story prompt.</li> <li> <strong>Fetch Story</strong>: fetchStory interacts with the Hugging Face API to generate and summarize a story based on the input.</li> <li> <strong>Navigation</strong>: If a story and summary are successfully fetched, the app navigates to the Detail screen to display the results.</li> </ul> <hr> <h3> Step 3: Displaying Story and Image on the Detail Screen </h3> <p><img src="https://img.php.cn/upload/article/000/000/000/173252011696327.jpg" alt="Building an Interactive Kids Story Generator with React Native and Hugging Face API" /></p> <p>The Detail screen retrieves the generated story, summarizes it, and displays an AI-generated cartoon image related to the story.</p><h4> Detail.js Code </h4> <pre class="brush:php;toolbar:false">import React, { useEffect, useState } from "react"; import { StyleSheet, View, Text, TouchableOpacity, ActivityIndicator, Image, ScrollView } from "react-native"; import { useLocalSearchParams, useRouter } from "expo-router"; import { HUGGING_FACE_KEY } from "../env"; import Ionicons from "@expo/vector-icons/Ionicons"; const Detail = () => { const params = useLocalSearchParams(); const { story, summary } = params; const [imageUri, setImageUri] = useState(null); const [loading, setLoading] = useState(false); const router = useRouter(); useEffect(() => { const fetchImage = async () => { setLoading(true); try { const response = await fetch("https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0", { method: "POST", headers: { Authorization: `Bearer ${HUGGING_FACE_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify ({ inputs: `Cartoonish ${summary}`, target_size: { width: 300, height: 300 } }), }); if (!response.ok) throw new Error(`Request failed: ${response.status}`); const blob = await response.blob(); const base64Data = await blobToBase64(blob); setImageUri(`data:image/jpeg;base64,${base64Data}`); } catch (error) { console.error("Error fetching image:", error); } finally { setLoading(false); } }; fetchImage(); }, []); const blobToBase64 = (blob) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result.split(",")[1]); reader.onerror = reject; reader.readAsDataURL(blob); }); }; return ( <ScrollView> <h3> Wrapping Up </h3> <p>This app is a great way to combine user input with AI models to create a dynamic storytelling experience. By using React Native, Hugging Face API, and Expo Router, we’ve created a simple yet powerful storytelling app that can entertain kids with custom-made stories and illustrations.</p>
The above is the detailed content of Building an Interactive Kids Story Generator with React Native and Hugging Face API. For more information, please follow other related articles on the PHP Chinese website!