route.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import { smartImageEdit, preciseImageEdit, creativeImageEdit, removeBackground, type AspectRatio } from '@/lib/fal-client';
  3. import { auth } from '@/lib/auth';
  4. import { deductCredits } from '@/lib/credit-service';
  5. import { db } from '@/lib/db';
  6. import { users } from '@/lib/schema';
  7. import { eq } from 'drizzle-orm';
  8. import { CREDIT_CONFIG } from '@/lib/constants';
  9. // 翻译消息
  10. const messages = {
  11. zh: {
  12. loginRequired: '请先登录后再使用图片编辑功能',
  13. userNotFound: '用户不存在',
  14. insufficientCredits: '积分不足,每次编辑需要10积分',
  15. noFile: '请上传图片文件',
  16. unsupportedImageFormat: '不支持的图片格式,请上传 JPG、PNG、WebP 或 AVIF 格式的图片',
  17. imageTooLarge: '图片文件过大,请上传小于 5MB 的图片',
  18. preciseNeedsPrompt: '精确编辑模式需要提供编辑指令',
  19. creativeNeedsPrompt: '创意编辑模式需要提供编辑指令',
  20. smartNeedsPrompt: '智能编辑模式需要提供编辑指令',
  21. processingError: '图片处理失败,请重试'
  22. },
  23. en: {
  24. loginRequired: 'Please log in first to use image editing features',
  25. userNotFound: 'User not found',
  26. insufficientCredits: 'Insufficient credits, 10 credits required per edit',
  27. noFile: 'Please upload an image file',
  28. unsupportedImageFormat: 'Unsupported image format, please upload JPG, PNG, WebP or AVIF format images',
  29. imageTooLarge: 'Image file too large, please upload images smaller than 5MB',
  30. preciseNeedsPrompt: 'Precise editing requires a prompt',
  31. creativeNeedsPrompt: 'Creative editing requires a prompt',
  32. smartNeedsPrompt: 'Smart editing requires a prompt',
  33. processingError: 'Image processing failed, please try again'
  34. }
  35. };
  36. // 获取翻译消息
  37. function getMessage(locale: string, key: keyof typeof messages.zh): string {
  38. const lang = (locale === 'zh' || locale === 'zh-CN') ? 'zh' : 'en';
  39. return messages[lang][key];
  40. }
  41. // 文件转换为 Data URL
  42. async function fileToDataUrl(file: File): Promise<string> {
  43. const arrayBuffer = await file.arrayBuffer();
  44. const base64 = Buffer.from(arrayBuffer).toString('base64');
  45. return `data:${file.type};base64,${base64}`;
  46. }
  47. // 支持的图片格式
  48. const SUPPORTED_IMAGE_TYPES = [
  49. 'image/jpeg',
  50. 'image/jpg',
  51. 'image/png',
  52. 'image/webp',
  53. 'image/avif'
  54. ];
  55. export async function POST(request: NextRequest) {
  56. try {
  57. const formData = await request.formData();
  58. const locale = (formData.get('locale') as string) || 'en';
  59. // 检查用户认证状态
  60. const session = await auth();
  61. if (!session?.user?.email) {
  62. return NextResponse.json(
  63. { success: false, error: getMessage(locale, 'loginRequired') },
  64. { status: 401 }
  65. );
  66. }
  67. // 获取用户信息
  68. const user = await db.query.users.findFirst({
  69. where: eq(users.email, session.user.email),
  70. });
  71. if (!user) {
  72. return NextResponse.json(
  73. { success: false, error: getMessage(locale, 'userNotFound') },
  74. { status: 404 }
  75. );
  76. }
  77. // 检查用户积分是否足够(先检查,但不扣除)
  78. if (user.credits < 10) {
  79. return NextResponse.json(
  80. {
  81. success: false,
  82. error: getMessage(locale, 'insufficientCredits')
  83. },
  84. { status: 402 } // Payment Required
  85. );
  86. }
  87. const file = formData.get('image') as File;
  88. const prompt = formData.get('prompt') as string;
  89. const action = (formData.get('action') as string) || 'smart';
  90. const guidanceScale = formData.get('guidance_scale') ? parseFloat(formData.get('guidance_scale') as string) : undefined;
  91. const strength = formData.get('strength') ? parseFloat(formData.get('strength') as string) : undefined;
  92. const aspectRatio = formData.get('aspect_ratio') as AspectRatio | null;
  93. if (!file) {
  94. return NextResponse.json(
  95. { success: false, error: getMessage(locale, 'noFile') },
  96. { status: 400 }
  97. );
  98. }
  99. // 验证文件类型
  100. if (!SUPPORTED_IMAGE_TYPES.includes(file.type)) {
  101. return NextResponse.json(
  102. {
  103. success: false,
  104. error: getMessage(locale, 'unsupportedImageFormat')
  105. },
  106. { status: 400 }
  107. );
  108. }
  109. // 验证文件大小(限制为 5MB)
  110. if (file.size > 5 * 1024 * 1024) {
  111. return NextResponse.json(
  112. { success: false, error: getMessage(locale, 'imageTooLarge') },
  113. { status: 400 }
  114. );
  115. }
  116. // 先进行图片编辑,不扣除积分
  117. const imageDataUrl = await fileToDataUrl(file);
  118. let result;
  119. switch (action) {
  120. case 'remove_background':
  121. case 'remove-background':
  122. result = await removeBackground(imageDataUrl, {
  123. aspect_ratio: aspectRatio || undefined,
  124. });
  125. break;
  126. case 'precise':
  127. if (!prompt) {
  128. return NextResponse.json(
  129. { success: false, error: getMessage(locale, 'preciseNeedsPrompt') },
  130. { status: 400 }
  131. );
  132. }
  133. result = await preciseImageEdit(imageDataUrl, prompt, {
  134. guidance_scale: guidanceScale,
  135. aspect_ratio: aspectRatio || undefined,
  136. });
  137. break;
  138. case 'creative':
  139. if (!prompt) {
  140. return NextResponse.json(
  141. { success: false, error: getMessage(locale, 'creativeNeedsPrompt') },
  142. { status: 400 }
  143. );
  144. }
  145. result = await creativeImageEdit(imageDataUrl, prompt, {
  146. guidance_scale: guidanceScale,
  147. aspect_ratio: aspectRatio || undefined,
  148. });
  149. break;
  150. case 'edit':
  151. case 'smart':
  152. default:
  153. if (!prompt) {
  154. return NextResponse.json(
  155. { success: false, error: getMessage(locale, 'smartNeedsPrompt') },
  156. { status: 400 }
  157. );
  158. }
  159. result = await smartImageEdit(imageDataUrl, prompt, {
  160. guidance_scale: guidanceScale,
  161. sync_mode: true,
  162. aspect_ratio: aspectRatio || undefined,
  163. });
  164. break;
  165. }
  166. // 只有在图片编辑成功后才扣除积分
  167. if (result.success) {
  168. const creditDeductResult = await deductCredits(
  169. user.id,
  170. CREDIT_CONFIG.COSTS.IMAGE_EDIT,
  171. action === 'remove_background' ? 'credit_description.background_removal' : `credit_description.image_edit:${prompt?.substring(0, 100) || 'Image Edit'}`,
  172. {
  173. action: action,
  174. prompt: prompt,
  175. file_size: file.size,
  176. file_type: file.type,
  177. aspect_ratio: aspectRatio,
  178. type: 'image_edit',
  179. }
  180. );
  181. // 返回成功结果,包含积分信息
  182. return NextResponse.json({
  183. success: true,
  184. data: result.data,
  185. error: null,
  186. action: action,
  187. credits: creditDeductResult.credits
  188. });
  189. } else {
  190. // 图片编辑失败,不扣除积分
  191. return NextResponse.json({
  192. success: false,
  193. data: null,
  194. error: result.error,
  195. action: action
  196. });
  197. }
  198. } catch (error) {
  199. console.error('Image edit API error:', error);
  200. // 尝试从 formData 中获取 locale,如果失败则默认为 'en'
  201. let locale = 'en';
  202. try {
  203. const formData = await request.formData();
  204. locale = (formData.get('locale') as string) || 'en';
  205. } catch {
  206. // 如果无法读取 formData,使用默认语言
  207. }
  208. return NextResponse.json(
  209. {
  210. success: false,
  211. error: error instanceof Error ? error.message : getMessage(locale, 'processingError')
  212. },
  213. { status: 500 }
  214. );
  215. }
  216. }
  217. export async function GET() {
  218. return NextResponse.json({
  219. message: '图片编辑 API',
  220. version: '1.0.0',
  221. supported_actions: ['smart', 'precise', 'creative', 'remove_background'],
  222. supported_formats: ['JPG', 'JPEG', 'PNG', 'WebP', 'AVIF'],
  223. max_file_size: '5MB',
  224. models: {
  225. smart: 'flux-kontext-dev',
  226. precise: 'flux-kontext-dev',
  227. creative: 'flux-kontext-dev',
  228. remove_background: 'flux-kontext-dev'
  229. },
  230. credit_cost: `${CREDIT_CONFIG.COSTS.IMAGE_EDIT} credits per edit`
  231. });
  232. }