0

0

使用 React Native 和 Hugging Face API 构建交互式儿童故事生成器

花韻仙語

花韻仙語

发布时间:2024-11-16 10:51:17

|

1183人浏览过

|

来源于dev.to

转载

在这篇文章中,我们将逐步构建一个 react native 应用程序,该应用程序使用 hugging face 强大的 ai 模型根据提示和年龄范围生成儿童故事。该应用程序允许用户输入提示,选择年龄范围,然后查看自定义故事以及总结故事的卡通图像。

特征

  1. 交互式故事生成:用户输入指导人工智能创建引人入胜的儿童故事。
  2. 摘要和可视化:故事被摘要并与人工智能生成的图像一起显示。
  3. 平滑的 ui 动画:动画使 ui 适应键盘输入。
  4. 导航和样式:使用 expo router 轻松导航并自定义样式,打造有吸引力的 ui。

让我们分解每个部分!


第 1 步:设置 react native 和 hugging face api

首先使用 expo 创建一个新的 react native 项目:

npx create-expo-app@latest kidsstoryapp
cd kidsstoryapp

在您的应用中设置 expo router 以便于导航,并安装您可能需要的任何其他依赖项,例如图标或动画。

第 2 步:创建故事生成器主屏幕

使用 React Native 和 Hugging Face API 构建交互式儿童故事生成器

在 home.js 文件中,我们设置了一个屏幕,用户可以在其中选择年龄范围、输入故事提示,然后按按钮生成故事。

白果AI论文
白果AI论文

论文AI生成学术工具,真实文献,免费不限次生成论文大纲 10 秒生成逻辑框架,10 分钟产出初稿,智能适配 80+学科。支持嵌入图表公式与合规文献引用

下载

home.js代码

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 (
    
      select age range
      
        {ageranges.map((range, index) => (
           handleagerangeselect(range)}
          >
            {range}
          
        ))}
      
      
      
        {isloading ?  : generate}
      
    
  );
};

const styles = stylesheet.create({
  container: { flex: 1, padding: 20, alignitems: "center", backgroundcolor: "#1c1c1c" },
  header: { fontsize: 20, fontweight: "bold", color: "#fff", marginvertical: 10 },
  checkboxcontainer: { flexdirection: "row", flexwrap: "wrap", justifycontent: "center", marginbottom: 20 },
  checkbox: { width: 60, height: 60, borderradius: 30, backgroundcolor: "#333", alignitems: "center", justifycontent: "center", margin: 10 },
  selectedcheckbox: { backgroundcolor: "#1fb28a" },
  checkboxlabel: { color: "#fff", fontsize: 14, fontweight: "bold" },
  textinput: { width: "100%", height: 150, backgroundcolor: "#333", color: "#fff", borderradius: 8, padding: 10, marginvertical: 20, fontsize: 16 },
  showbutton: { backgroundcolor: "#1fb28a", borderradius: 8, paddingvertical: 10, paddinghorizontal: 20, margintop: 10 },
  showbuttontext: { color: "#fff", fontsize: 16, fontweight: "bold" },
});

export default home;

home.js 的关键组件

  • 文本输入和年龄选择器:允许用户选择年龄范围并输入故事提示。
  • fetch story:fetchstory 与 hugging face api 交互,根据输入生成和总结故事。
  • 导航:如果成功获取故事和摘要,应用程序将导航到详细信息屏幕以显示结果。

步骤 3:在详细信息屏幕上显示故事和图像

使用 React Native 和 Hugging Face API 构建交互式儿童故事生成器

详细信息屏幕检索生成的故事,对其进行总结,并显示人工智能生成的与故事相关的卡通图像。

detail.js 代码

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 (
    
       router.back()}>
        
      
      {loading ? (
        
      ) : imageUri ? (
        
      ) : (
        No image generated yet.
      )}
      {story}
    
  );
};

export default Detail;

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: "#1c1c1c" },
  header: { fontSize: 24, color: "#ffffff", marginVertical: 16 },
  text: { color: "#ffffff" },
  image: { width: 300, height: 300, marginTop: 20, borderRadius: 10, alignSelf: "center" },
});

总结

这个应用程序是将用户输入与人工智能模型相结合以创建动态讲故事体验的好方法。通过使用 react native、hugging face api 和 expo router,我们创建了一个简单但功能强大的讲故事应用程序,可以通过定制的故事和插图来娱乐孩子们。

相关专题

更多
js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

510

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

244

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

254

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

5270

2023.08.17

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

476

2023.09.01

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

206

2023.09.04

Js中concat和push的区别
Js中concat和push的区别

Js中concat和push的区别:1、concat用于将两个或多个数组合并成一个新数组,并返回这个新数组,而push用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度;2、concat不会修改原始数组,是创建新的数组,而push会修改原数组,将新元素添加到原数组的末尾等等。本专题为大家提供concat和push相关的文章、下载、课程内容,供大家免费下载体验。

217

2023.09.14

js截取字符串的方法介绍
js截取字符串的方法介绍

JavaScript字符串截取方法,包括substring、slice、substr、charAt和split方法。这些方法可以根据具体需求,灵活地截取字符串的不同部分。在实际开发中,根据具体情况选择合适的方法进行字符串截取,能够提高代码的效率和可读性 。

218

2023.09.21

php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

3

2026.01.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号