iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎨

I Built SlideCraft: A Tool to Partially Regenerate AI-Generated Slides

に公開

What is this?

I created "SlideCraft," a web application that allows you to upload PDF slides and use AI to regenerate only the specific slides you want to fix. It is a completely client-side application built by combining React Router v7, the Google Gemini API, and the Origin Private File System (OPFS).

https://www.slidecraft.work

https://github.com/techtalkjp/slidecraft

The Background

When generating presentation materials with tools like Nano Banana Pro or Google Notebook LM, you might find that 17 out of 20 slides look great, but 3 are just not quite right.

This leads to a problem: if you adjust the prompt and regenerate, even those 17 good slides might change. On the other hand, manually fixing them in PowerPoint is time-consuming. There wasn't a tool available to address the common request of "I only want to fix these 3 slides with AI." In this article, I will introduce some of the interesting technical points I encountered while developing SlideCraft.

Data Persistence with the Origin Private File System (OPFS)

Why I chose OPFS

SlideCraft runs entirely on the client side. Since I wanted a design without a backend, the challenge was where to store the user's project data.

The options were localStorage, IndexedDB, and OPFS. localStorage has strict capacity limits and is unsuitable for handling images. IndexedDB has sufficient capacity, but it requires abstraction to express the concept of a file system through a Key-Value API.

I chose OPFS because you can use the file system concept exactly as it is. You can treat projects as directories and slide images or metadata as files. It is intuitive for developers, and the design makes it easy to incorporate future extensions that integrate with the File System Access API.

Implementation points

// Excerpt from storage.client.ts
export async function writeFile(path: string, content: string | Blob): Promise<void> {
  const root = await navigator.storage.getDirectory()
  const parts = path.split('/').filter(Boolean)
  const fileName = parts.pop()
  if (!fileName) throw new Error('Invalid path')

  let current = root
  for (const part of parts) {
    current = await current.getDirectoryHandle(part, { create: true })
  }

  const fileHandle = await current.getFileHandle(fileName, { create: true })
  const writable = await fileHandle.createWritable()
  await writable.write(content)
  await writable.close()
}

It splits the path by /, creates directories recursively, and finally writes the file. With the { create: true } option, missing directories or files are created automatically.

It is also convenient that you can handle both binary data (Blob) and text (JSON strings) with the same interface. I save metadata as JSON and slide images as Blobs.

Since OPFS also provides createSyncAccessHandle() which can be accessed synchronously from Web Workers, it is possible to offload heavy processing to a Worker in the future.

React Router v7 clientLoader/clientAction Patterns

Data fetching without a server

In React Router v7, you can use clientLoader and clientAction in addition to the traditional loader and action. These are data fetching and mutation functions that run exclusively on the client side.

Since SlideCraft has no backend, all data operations are performed on the client. I use clientLoader to load project data from OPFS and clientAction to handle slide selection and image updates.

// From routes/editor.tsx
export const clientLoader = async ({ params }: Route.ClientLoaderArgs) => {
  const projectId = params.projectId
  const slideIndex = Number(params.slideIndex)

  const project = await loadProject(projectId)
  const slide = project.slides[slideIndex]
  const originalImagePath = slide.originalImagePath

  return { project, slide, slideIndex, originalImagePath }
}

export const clientAction = async ({ request, params }: Route.ClientActionArgs) => {
  const formData = await request.formData()
  const intent = formData.get('intent')

  switch (intent) {
    case 'selectCandidate':
      // Select generated candidate image
      return await selectCandidateAction(params, formData)
    case 'resetToOriginal':
      // Reset to original image
      return await resetToOriginalAction(params)
    // ...
  }
}

Why clientAction instead of useState?

In the slide editor, there are actions like "select a generated candidate image" or "reset to the original image." If these are managed with useState, the logic for state updates tends to get scattered across components.

By using clientAction, state changes are expressed as explicit form submissions. By combining it with React Router v7's useFetcher, you can automatically track the pending state during asynchronous processes.

const fetcher = useFetcher()
const isUpdating = fetcher.state !== 'idle'

// Form submission
<fetcher.Form method="post">
  <input type="hidden" name="intent" value="selectCandidate" />
  <button disabled={isUpdating}>Select</button>
</fetcher.Form>

Reading (clientLoader) and writing (clientAction) are clearly separated, making the code much easier to understand.

Parallel Image Generation and Cost Calculation with Gemini API

Parallel generation of multiple variations

When regenerating a slide, I generate multiple variations for a single slide. When a user inputs a prompt like "make it simpler," it generates three candidate images simultaneously.

// From gemini-api.client.ts
export async function generateSlideImages(
  apiKey: string,
  imageBlob: Blob,
  prompt: string,
  count: number = 3
): Promise<GenerationResult[]> {
  const base64Image = await blobToBase64(imageBlob)

  const promises = Array.from({ length: count }, () =>
    callGeminiAPI(apiKey, base64Image, prompt)
  )

  const results = await Promise.all(promises)
  return results
}

By executing in parallel with Promise.all, I avoid the waiting time for generating three images becoming three times longer. I focused on returning responses as quickly as possible without hitting the Gemini API rate limits.

Visualization of costs

AI image generation comes with costs. To ensure users can use it with peace of mind, I display a cost estimate before generation.

// From cost-calculator.ts
const GEMINI_PRICING = {
  image_2k: 0.134,  // US dollars per 2K image
  image_4k: 0.24,
}

export function calculateCost(slideCount: number, resolution: '2k' | '4k'): number {
  const pricePerImage = resolution === '2k'
    ? GEMINI_PRICING.image_2k
    : GEMINI_PRICING.image_4k
  return slideCount * pricePerImage
}

Furthermore, I fetch exchange rates from exchangerate-api to display prices in Japanese Yen. The rates are cached for 24 hours to minimize API calls.

Though it is a small feature, I focused on cost transparency, which is often overlooked in AI tools. I believe that being able to know exactly how much it costs when you press a button allows users to use the service with confidence.

Conclusion

While developing SlideCraft, I really felt the evolution of the browser. The file system abstraction via OPFS, client-side data fetching with React Router v7, and direct access to the Gemini API—by combining these, you can create rich AI applications even without a backend.

Please give it a try. If you have any questions or feedback, I am waiting for them on GitHub Issues.

https://www.slidecraft.work

https://github.com/techtalkjp/slidecraft

GitHubで編集を提案

Discussion