Skip to content

Commit

Permalink
Merge pull request #89 from trpfrog/change-api-origin
Browse files Browse the repository at this point in the history
trpfrog-diffusion が更新されない問題の修正
  • Loading branch information
trpfrog authored Nov 15, 2024
2 parents d4b4996 + 223bb26 commit 1f6a1c8
Show file tree
Hide file tree
Showing 17 changed files with 1,267 additions and 603 deletions.
4 changes: 2 additions & 2 deletions apps/image-generation/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
"@langchain/core": "^0.2.17",
"@langchain/openai": "^0.2.4",
"@trpfrog.net/constants": "workspace:*",
"@trpfrog.net/utils": "workspace:*",
"date-fns": "^4.1.0",
"hono": "^4.6.5",
"ts-dedent": "^2.2.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20240718.0",
"@trpfrog.net/config-typescript": "workspace:*",
"wrangler": "^3.65.1"
"@trpfrog.net/config-typescript": "workspace:*"
}
}
16 changes: 12 additions & 4 deletions apps/image-generation/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { services } from '@trpfrog.net/constants'
import { differenceInMinutes } from 'date-fns'
import { Context, Hono } from 'hono'
import { env } from 'hono/adapter'
Expand Down Expand Up @@ -39,18 +40,19 @@ async function fetchCacheStatus(c: Context<Env>) {
}

export const app = new Hono<Env>()
.basePath(services.imageGeneration.basePath)
.use(prettyJSON())
.use(trimTrailingSlash())
.use(cors())
.get('/current', cache({ cacheName: 'current-image', cacheControl: 'max-age-3600' }), async c => {
.get('/current', cache({ cacheName: 'current-image', cacheControl: 'max-age=3600' }), async c => {
const arrayBuffer = await c.env.DIFFUSION_KV.get('current-image', {
type: 'arrayBuffer',
})
return c.newResponse(arrayBuffer)
})
.get(
'/current/metadata',
cache({ cacheName: 'current-metadata', cacheControl: 'max-age-3600' }),
cache({ cacheName: 'current-metadata', cacheControl: 'max-age=3600' }),
async c => {
const data = await c.env.DIFFUSION_KV.get('current-metadata', { type: 'json' })
return c.json(MetadataSchema.parse(data))
Expand All @@ -60,12 +62,18 @@ export const app = new Hono<Env>()
const data = await fetchCacheStatus(c)
return c.json(data)
})
.post('/update', requiresApiKey(), async c => {
.post('/update', async c => {
const { OPENAI_API_KEY, HUGGINGFACE_TOKEN } = env(c)
const { shouldCache, waitMinutes } = await fetchCacheStatus(c)
const isForceUpdate = c.req.query('force') === 'true'

// Check if the request is authorized
if (isForceUpdate) {
await requiresApiKey()(c, async () => {})
}

// Skip update if the last update was within 180 minutes
if (c.req.query('force') !== 'true' && shouldCache) {
if (!isForceUpdate && shouldCache) {
return c.json({
status: 'skipped',
message: `Minimum update interval is 180 minutes, please wait ${waitMinutes} minutes.`,
Expand Down
6 changes: 3 additions & 3 deletions apps/image-generation/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ export {
import type { AppType } from './app'

export function createTrpFrogImageGenerationClient(env: 'development' | 'production' | 'test') {
const endpoint = services.imageGeneration.endpoint(env)
if (endpoint == null) {
const origin = services.imageGeneration.origin(env)
if (origin == null) {
throw new Error('Image generation service is not available in this environment')
}
return hc<AppType>(endpoint)
return hc<AppType>(origin).icongen
}
52 changes: 36 additions & 16 deletions apps/image-generation/src/devPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { services } from '@trpfrog.net/constants'
import { createURL } from '@trpfrog.net/utils'
import { Env, Hono } from 'hono'
import { env } from 'hono/adapter'
import { basicAuth } from 'hono/basic-auth'
Expand All @@ -10,12 +12,16 @@ export const adminApp = new Hono<Env>()

// Basic auth middleware
adminApp.use(async (c, next) => {
const { TRPFROG_FUNCTIONS_SECRET } = env(c)
const handler = basicAuth({
username: 'admin',
password: z.string().parse(TRPFROG_FUNCTIONS_SECRET),
})
await handler(c, next)
if (env(c).NODE_ENV === 'development') {
await next()
} else {
const { TRPFROG_FUNCTIONS_SECRET } = env(c)
const handler = basicAuth({
username: 'admin',
password: z.string().parse(TRPFROG_FUNCTIONS_SECRET),
})
await handler(c, next)
}
})

// Playground
Expand All @@ -25,15 +31,18 @@ adminApp.post('/playground/prompt', async c => {
const promptRes = await generateRandomTrpFrogPrompt(randomWords, z.string().parse(OPENAI_API_KEY))
return c.json({
usedWords: randomWords.join(','),
prompt: promptRes.prompt,
translated: promptRes.translated,
...promptRes,
})
})

// Update image
adminApp.post('/force-update', c => {
const { TRPFROG_FUNCTIONS_SECRET } = env(c)
return fetch('/update?force', {
const { TRPFROG_FUNCTIONS_SECRET, NODE_ENV } = env(c)
const node_env = z.enum(['development', 'production', 'test']).catch('production').parse(NODE_ENV)
const endpoint = createURL('/update', services.imageGeneration.origin(node_env), {
force: 'true',
})
return fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand All @@ -58,22 +67,33 @@ adminApp.get('/', async c => {
<h1>image-generation admin page</h1>

<h2>Current Image</h2>
<img id="current-image" src="/current" />
<img id="current-image" src="/icongen/current" />

<h2>Metadata</h2>
<pre id="current-metadata" hx-get="/current/metadata?pretty" hx-trigger="load">
<pre id="current-metadata" hx-get="/icongen/current/metadata?pretty" hx-trigger="load">
loading...
</pre>

<h2>Operations</h2>
<form action="/generate" method="post">
<button type="submit">Request Update</button>
</form>
<button
hx-post="/icongen/update"
hx-trigger="click"
hx-on="alert('Update Request has been triggered')"
>
Request Update
</button>
<button
hx-post="/icongen/admin/force-update"
hx-trigger="click"
hx-on="alert('Force Update has been triggered')"
>
Force Update
</button>

<h2>Playground</h2>
<h3>Generate prompt</h3>
<button
hx-post="/admin/playground/prompt?pretty"
hx-post="/icongen/admin/playground/prompt?pretty"
hx-trigger="click"
hx-target="#playground-generate-prompt-result"
>
Expand Down
Loading

0 comments on commit 1f6a1c8

Please sign in to comment.