feat: Implement PDF recipe parser and quick import service for file and URL inputs

This commit is contained in:
Nils-Johan Gynther
2026-04-14 22:24:28 +02:00
parent e90fd2d670
commit 1ce1318bf5
10 changed files with 758 additions and 194 deletions
+6 -1
View File
@@ -17,15 +17,20 @@
"@prisma/client": "^6.12.0", "@prisma/client": "^6.12.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.15.1", "class-validator": "^0.15.1",
"multer": "^1.4.5-lts.2",
"pdf-parse": "^1.1.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1" "rxjs": "^7.8.1",
"tesseract.js": "^6.0.1"
}, },
"devDependencies": { "devDependencies": {
"@nestjs/cli": "^10.3.0", "@nestjs/cli": "^10.3.0",
"@nestjs/schematics": "^10.1.1", "@nestjs/schematics": "^10.1.1",
"@nestjs/testing": "^10.3.0", "@nestjs/testing": "^10.3.0",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/multer": "^1.4.12",
"@types/node": "^22.15.29", "@types/node": "^22.15.29",
"@types/pdf-parse": "^1.1.5",
"prisma": "^6.12.0", "prisma": "^6.12.0",
"typescript": "^5.4.5" "typescript": "^5.4.5"
} }
@@ -0,0 +1,8 @@
import { IsOptional, IsString, MaxLength } from 'class-validator';
export class QuickImportDto {
@IsOptional()
@IsString()
@MaxLength(2048)
input?: string;
}
@@ -0,0 +1,116 @@
/**
* Parser för PDF-filer
* Använder pdf-parse för att extrahera text från PDF-dokument
*/
import { RecipeParser, ParsedRecipe } from './base.parser';
import * as pdf from 'pdf-parse';
export class PdfRecipeParser extends RecipeParser {
canHandle(url: string): boolean {
// Denna parser hanterar PDF-filer
const normalized = url.toLowerCase();
return normalized.endsWith('.pdf');
}
async parse(fileBuffer: Buffer): Promise<ParsedRecipe> {
console.log('[PdfParser] Parsing PDF file...');
try {
// Extrahera text från PDF
const data = await pdf(fileBuffer);
const text = data.text;
console.log('[PdfParser] Extraherad text längd:', text.length);
// Parsa texten till receptstruktur
return this.parseRecipeText(text);
} catch (err) {
console.error('[PdfParser] Fel vid PDF-parsing:', err);
throw new Error('Kunde inte tolka PDF-filen. Kontrollera att det är ett giltigt recept.');
}
}
/**
* Parsar råtext från PDF till strukturerat recept
* Försöker identifiera receptnamn, ingredienser och instruktioner
*/
private parseRecipeText(text: string): ParsedRecipe {
const lines = text.split('\n').map(line => line.trim()).filter(line => line.length > 0);
let name = 'Okänt recept';
let description = '';
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
let instructions = '';
let currentSection: 'name' | 'description' | 'ingredients' | 'instructions' | null = null;
// Försök hitta receptnamn (stor text i början)
const titleMatch = text.match(/^[A-ZÅÄÖ\s]+/i);
if (titleMatch) {
name = titleMatch[0].trim();
}
// Analysera texten rad för rad
for (const line of lines) {
// Hoppa över tomma rader
if (!line || line.length === 0) continue;
// Detektera sektioner
if (line.toLowerCase().includes('ingredienser')) {
currentSection = 'ingredients';
continue;
}
if (line.toLowerCase().includes('tillvägagångssätt') ||
line.toLowerCase().includes('instruktioner') ||
line.toLowerCase().includes('gör så här')) {
currentSection = 'instructions';
continue;
}
// Samla in innehåll baserat på aktuell sektion
switch (currentSection) {
case 'ingredients':
if (line.toLowerCase().includes('tillvägagångssätt') ||
line.toLowerCase().includes('instruktioner')) {
currentSection = 'instructions';
break;
}
// Parsa ingrediensrad
const ingredient = this.parseIngredientLine(line);
if (ingredient) {
ingredients.push(ingredient);
}
break;
case 'instructions':
if (instructions.length > 0) {
instructions += '\n';
}
instructions += line;
break;
default:
// Om vi inte har hittat ingredienser än, kan detta vara beskrivning
if (ingredients.length === 0 && !description.includes(line)) {
if (description.length > 0) {
description += ' ';
}
description += line;
}
break;
}
}
// Om vi inte hittade något receptnamn, försök använda första meningsfulla raden
if (name === 'Okänt recept' && lines.length > 0) {
name = lines[0].length > 50 ? lines[0].substring(0, 50) + '...' : lines[0];
}
return {
name,
description: description || undefined,
ingredients,
instructions: instructions || undefined,
};
}
}
@@ -0,0 +1,25 @@
import { Controller, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { QuickImportService, QuickImportResult } from './quick-import.service';
@Controller('quick-import')
export class QuickImportController {
constructor(private readonly quickImportService: QuickImportService) {}
@Post()
@UseInterceptors(FileInterceptor('file'))
async importFromInput(
@Body() body: { input: string },
@UploadedFile() file?: Express.Multer.File
): Promise<QuickImportResult> {
// Om en fil laddats upp, använd filen
if (file) {
console.log('[QuickImportController] Mottog fil:', file.originalname);
return this.quickImportService.importFromInput(file.originalname, file.buffer);
}
// Annars använd text-input (URL)
console.log('[QuickImportController] Mottog text-input:', body.input);
return this.quickImportService.importFromInput(body.input);
}
}
@@ -1,4 +1,7 @@
import { Controller, Post, Body } from '@nestjs/common'; import { Body, Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { QuickImportDto } from './dto/quick-import.dto';
import { QuickImportService, QuickImportResult } from './quick-import.service'; import { QuickImportService, QuickImportResult } from './quick-import.service';
@Controller('quick-import') @Controller('quick-import')
@@ -6,9 +9,20 @@ export class QuickImportController {
constructor(private readonly quickImportService: QuickImportService) {} constructor(private readonly quickImportService: QuickImportService) {}
@Post() @Post()
@UseInterceptors(
FileInterceptor('file', {
storage: memoryStorage(),
limits: { fileSize: 10 * 1024 * 1024 },
}),
)
async importFromInput( async importFromInput(
@Body() body: { input: string } @Body() body: QuickImportDto,
@UploadedFile() file?: Express.Multer.File,
): Promise<QuickImportResult> { ): Promise<QuickImportResult> {
return this.quickImportService.importFromInput(body.input); if (file) {
return this.quickImportService.importFromUpload(file);
}
return this.quickImportService.importFromInput(body?.input ?? '');
} }
} }
@@ -0,0 +1,242 @@
import { Injectable, BadRequestException } from '@nestjs/common';
import { IcaRecipeParser } from './parsers/ica.parser';
import { GenericRecipeParser } from './parsers/generic.parser';
import { PdfRecipeParser } from './parsers/pdf.parser';
import { RecipeParser } from './parsers/base.parser';
export interface QuickImportResult {
markdown: string;
source: 'ica' | 'pdf' | 'other';
}
@Injectable()
export class QuickImportService {
/**
* Detekterar typ av input (URL eller fil) och importerar från lämplig källa
*/
async importFromInput(input: string, fileBuffer?: Buffer): Promise<QuickImportResult> {
input = input.trim();
console.log('[QuickImport] Mottog input:', input);
if (!input) {
throw new BadRequestException('Du måste ange en URL eller ladda upp en fil');
}
// Detektera typ
const isUrl = this.isUrl(input);
const isPdf = this.isPdfPath(input);
console.log('[QuickImport] isUrl:', isUrl, 'isPdf:', isPdf);
if (isUrl) {
console.log('[QuickImport] Detekterade URL, försöker scrapa...');
return this.scrapeRecipeFromUrl(input);
} else if (isPdf) {
console.log('[QuickImport] Detekterade PDF-fil');
if (!fileBuffer) {
throw new BadRequestException('PDF-fil kräver filinnehåll (fileBuffer)');
}
return this.parsePdfFile(fileBuffer);
} else {
console.log('[QuickImport] Input är inte URL eller PDF');
throw new BadRequestException(
'Ogültig input. Ange en gyltig URL (t.ex. ica.se/recept/...) eller ladda upp en PDF-fil'
);
}
}
/**
* Kontrollerar om input är en URL
*/
private isUrl(input: string): boolean {
try {
new URL(input);
return true;
} catch {
return false;
}
}
/**
* Kontrollerar om input är en PDF-filsökväg
*/
private isPdfPath(input: string): boolean {
const normalized = input.toLowerCase();
return normalized.endsWith('.pdf');
}
/**
* Skrapar recept från en URL
*
* Använder site-specifika parsers om tillgängliga,
* annars fallback till generisk parser.
*
* @param url URL till receptsidan
* @returns Markdown-format
*/
private async scrapeRecipeFromUrl(url: string): Promise<QuickImportResult> {
try {
console.log('[QuickImport] Hämtar HTML från:', url);
// Hämta HTML från URL
const response = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
},
});
console.log('[QuickImport] HTTP status:', response.status);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const html = await response.text();
console.log('[QuickImport] HTML längd:', html.length, 'tecken');
// Välj lämplig parser
const parsers: RecipeParser[] = [
new IcaRecipeParser(),
new GenericRecipeParser(),
];
let recipe = null;
for (const parser of parsers) {
if (parser.canHandle(url)) {
console.log('[QuickImport] Använder parser:', parser.constructor.name);
recipe = parser.parse(html);
break;
}
}
if (!recipe) {
throw new Error('Ingen parserutrustning tillgänglig');
}
console.log('[QuickImport] Parsad recept:', {
name: recipe.name,
ingredienser: recipe.ingredients.length,
});
if (!recipe.name) {
throw new Error('Kunde inte hitta receptnamn på sidan. Försök med en annan länk.');
}
// Konvertera till Markdown-format
const markdown = this.recipeToMarkdown(recipe, url);
console.log('[QuickImport] Markdown genererad, längd:', markdown.length);
// Detektera källa från URL
let source: 'ica' | 'pdf' | 'other' = 'other';
if (/ica\.se/i.test(url)) {
source = 'ica';
}
return {
markdown,
source,
};
} catch (err) {
const message = err instanceof Error ? err.message : 'Okänt fel vid scraping';
console.error('[QuickImport] ERROR:', message);
throw new BadRequestException(
`Kunde inte hämta recept: ${message}. Kontrollera att länken är korrekt och försök igen.`
);
}
}
/**
* Parsar PDF-fil och konverterar till Markdown
*/
private async parsePdfFile(fileBuffer: Buffer): Promise<QuickImportResult> {
try {
console.log('[QuickImport] Parsar PDF-fil...');
const pdfParser = new PdfRecipeParser();
const recipe = await pdfParser.parse(fileBuffer);
console.log('[QuickImport] PDF parsad:', {
name: recipe.name,
ingredienser: recipe.ingredients.length,
});
if (!recipe.name) {
throw new Error('Kunde inte hitta receptnamn i PDF-filen.');
}
// Konvertera till Markdown-format
const markdown = this.recipeToMarkdown(recipe);
console.log('[QuickImport] Markdown genererad från PDF, längd:', markdown.length);
return {
markdown,
source: 'pdf',
};
} catch (err) {
const message = err instanceof Error ? err.message : 'Okänt fel vid PDF-parsing';
console.error('[QuickImport] PDF ERROR:', message);
throw new BadRequestException(
`Kunde inte läsa PDF-filen: ${message}. Kontrollera att det är ett giltigt recept i PDF-format.`
);
}
}
/**
* Konvertera receptobjekt till Markdown-format
*/
private recipeToMarkdown(
recipe: {
name: string;
description?: string;
ingredients: Array<{
quantity: number;
unit: string;
name: string;
note?: string;
}>;
instructions?: string;
},
sourceUrl?: string,
): string {
const lines: string[] = [];
// Titel
lines.push(`# ${recipe.name}`);
lines.push('');
// Beskrivning
if (recipe.description) {
lines.push(recipe.description);
lines.push('');
}
// Ingredienser
if (recipe.ingredients.length > 0) {
lines.push('## Ingredienser');
for (const ing of recipe.ingredients) {
const quantity = ing.quantity > 0 ? `${ing.quantity} ` : '';
const unit = ing.unit ? `${ing.unit} ` : '';
const note = ing.note ? ` (${ing.note})` : '';
lines.push(`- ${quantity}${unit}${ing.name}${note}`);
}
lines.push('');
}
// Instruktioner
if (recipe.instructions) {
lines.push('## Tillvägagångssätt');
lines.push(recipe.instructions);
lines.push('');
}
// Källa
if (sourceUrl) {
lines.push('---');
lines.push('');
lines.push(`Källa: [${sourceUrl}](${sourceUrl})`);
}
return lines.join('\n');
}
}
+212 -37
View File
@@ -1,48 +1,87 @@
import { Injectable, BadRequestException } from '@nestjs/common'; import {
BadRequestException,
Injectable,
ServiceUnavailableException,
UnsupportedMediaTypeException,
} from '@nestjs/common';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as pdfParse from 'pdf-parse';
import { createWorker } from 'tesseract.js';
import { IcaRecipeParser } from './parsers/ica.parser'; import { IcaRecipeParser } from './parsers/ica.parser';
import { GenericRecipeParser } from './parsers/generic.parser'; import { GenericRecipeParser } from './parsers/generic.parser';
import { RecipeParser } from './parsers/base.parser'; import { RecipeParser } from './parsers/base.parser';
export interface QuickImportResult { export interface QuickImportResult {
markdown: string; markdown: string;
source: 'ica' | 'pdf' | 'other'; source: 'ica' | 'pdf' | 'image' | 'other';
} }
type UploadKind = 'pdf' | 'image';
@Injectable() @Injectable()
export class QuickImportService { export class QuickImportService {
/** /**
* Detekterar typ av input (URL eller filsökväg) och importerar från lämplig källa * Detekterar typ av input (URL eller filsökväg) och importerar från lämplig källa
*/ */
async importFromInput(input: string): Promise<QuickImportResult> { async importFromInput(input: string): Promise<QuickImportResult> {
input = input.trim(); const trimmed = input.trim();
console.log('[QuickImport] Mottog input:', input); console.log('[QuickImport] Mottog input:', trimmed);
if (!input) { if (!trimmed) {
throw new BadRequestException('Du måste ange en URL eller filsökväg'); throw new BadRequestException('Du måste ange en URL eller ladda upp en fil');
} }
// Detektera typ if (this.isUrl(trimmed)) {
const isUrl = this.isUrl(input);
const isPdf = this.isPdfPath(input);
console.log('[QuickImport] isUrl:', isUrl, 'isPdf:', isPdf);
if (isUrl) {
console.log('[QuickImport] Detekterade URL, försöker scrapa...'); console.log('[QuickImport] Detekterade URL, försöker scrapa...');
return this.scrapeRecipeFromUrl(input); return this.scrapeRecipeFromUrl(trimmed);
} else if (isPdf) { }
console.log('[QuickImport] Detekterade PDF-fil');
if (this.looksLikeLocalFile(trimmed)) {
console.log('[QuickImport] Försöker läsa lokal fil:', trimmed);
try {
const buffer = await fs.readFile(trimmed);
return this.importFromUpload({
buffer,
originalname: path.basename(trimmed),
mimetype: this.getMimeTypeFromExtension(trimmed),
} as Express.Multer.File);
} catch (error) {
console.error('[QuickImport] Kunde inte läsa lokal fil:', error);
throw new BadRequestException( throw new BadRequestException(
'PDF-import under utveckling. Försök med en URL från ICA.se eller annat receptsida.' 'Kunde inte läsa filen. Använd filuppladdning i gränssnittet eller kontrollera sökvägen.',
);
} else {
console.log('[QuickImport] Input är inte URL eller PDF');
throw new BadRequestException(
'Ogültig input. Ange en gyltig URL (t.ex. ica.se/recept/...) eller filsökväg'
); );
} }
} }
throw new BadRequestException(
'Ogiltig input. Ange en giltig URL eller ladda upp en PDF- eller bildfil.',
);
}
async importFromUpload(file: Express.Multer.File): Promise<QuickImportResult> {
if (!file?.buffer) {
throw new BadRequestException('Ingen fil skickades med.');
}
console.log('[QuickImport] Mottog uppladdad fil:', file.originalname, file.mimetype);
const kind = this.getUploadKind(file);
if (kind === 'pdf') {
const text = await this.extractTextFromPdf(file.buffer);
return {
markdown: this.normalizeImportedTextToMarkdown(text, file.originalname),
source: 'pdf',
};
}
const text = await this.extractTextFromImage(file.buffer);
return {
markdown: this.normalizeImportedTextToMarkdown(text, file.originalname),
source: 'image',
};
}
/** /**
* Kontrollerar om input är en URL * Kontrollerar om input är en URL
*/ */
@@ -55,12 +94,157 @@ export class QuickImportService {
} }
} }
/** private looksLikeLocalFile(input: string): boolean {
* Kontrollerar om input är en PDF-filsökväg
*/
private isPdfPath(input: string): boolean {
const normalized = input.toLowerCase(); const normalized = input.toLowerCase();
return normalized.endsWith('.pdf'); return /[\\/]/.test(input) || /\.(pdf|png|jpg|jpeg|webp|bmp)$/i.test(normalized);
}
private getMimeTypeFromExtension(filename: string): string {
const ext = path.extname(filename).toLowerCase();
if (ext === '.pdf') return 'application/pdf';
if (ext === '.png') return 'image/png';
if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
if (ext === '.webp') return 'image/webp';
if (ext === '.bmp') return 'image/bmp';
return 'application/octet-stream';
}
private getUploadKind(
file: Pick<Express.Multer.File, 'mimetype' | 'originalname'>,
): UploadKind {
const type = (file.mimetype ?? '').toLowerCase();
const name = (file.originalname ?? '').toLowerCase();
if (type.includes('pdf') || name.endsWith('.pdf')) {
return 'pdf';
}
if (
type.startsWith('image/') ||
['.png', '.jpg', '.jpeg', '.webp', '.bmp'].some((ext) => name.endsWith(ext))
) {
return 'image';
}
throw new UnsupportedMediaTypeException(
'Endast PDF, PNG, JPG, JPEG, WEBP och BMP stöds.',
);
}
private async extractTextFromPdf(buffer: Buffer): Promise<string> {
try {
const result = await pdfParse(buffer);
const text = result.text?.replace(/\u0000/g, '').trim();
if (!text) {
throw new BadRequestException(
'PDF-filen saknar läsbar text. Prova bildimport om det är en skannad sida.',
);
}
return text;
} catch (error) {
if (error instanceof BadRequestException) {
throw error;
}
console.error('[QuickImport] PDF ERROR:', error);
throw new ServiceUnavailableException('PDF-importen misslyckades.');
}
}
private async extractTextFromImage(buffer: Buffer): Promise<string> {
const worker = await createWorker('swe+eng');
try {
const result = await worker.recognize(buffer);
const text = result.data.text?.trim();
if (!text) {
throw new BadRequestException('Ingen text hittades i bilden.');
}
return text;
} catch (error) {
if (error instanceof BadRequestException) {
throw error;
}
console.error('[QuickImport] OCR ERROR:', error);
throw new ServiceUnavailableException('OCR-importen misslyckades.');
} finally {
await worker.terminate();
}
}
private normalizeImportedTextToMarkdown(text: string, sourceName?: string): string {
const cleanedText = text
.replace(/\r/g, '')
.replace(/[ \t]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim();
if (!cleanedText) {
throw new BadRequestException('Ingen läsbar text hittades i filen.');
}
const title = cleanedText.split('\n').find((line) => line.trim().length > 3)?.trim() ?? 'Importerat recept';
const ingredients: string[] = [];
const instructions: string[] = [];
let section: 'unknown' | 'ingredients' | 'instructions' = 'unknown';
for (const rawLine of cleanedText.split('\n')) {
const line = rawLine.trim();
if (!line || line === title) {
continue;
}
const lower = line.toLowerCase();
if (/^ingred/i.test(lower)) {
section = 'ingredients';
continue;
}
if (/^(gör så här|gor sa har|instruktioner|tillvägagångssätt|tillvagagangssatt|method|instructions)/i.test(lower)) {
section = 'instructions';
continue;
}
if (section === 'unknown') {
section = this.looksLikeIngredientLine(line) ? 'ingredients' : 'instructions';
}
if (section === 'ingredients') {
ingredients.push(line.startsWith('-') ? line : `- ${line}`);
} else {
instructions.push(line);
}
}
return [
`# ${title}`,
'',
'## Ingredienser',
...(ingredients.length > 0 ? ingredients : ['- Komplettera ingredienser manuellt']),
'',
'## Tillvägagångssätt',
...(instructions.length > 0 ? instructions : ['Komplettera tillagningsstegen manuellt.']),
'',
sourceName ? `Källa: ${sourceName}` : '',
]
.filter(Boolean)
.join('\n');
}
private looksLikeIngredientLine(line: string): boolean {
return (
/^[-*•]\s+/.test(line) ||
/^\d+[.,]?\d*\s+/.test(line) ||
/\b(g|kg|hg|mg|ml|dl|cl|l|tsk|msk|krm|st|pkt|förp|klyfta)\b/i.test(line)
);
} }
/** /**
@@ -76,7 +260,6 @@ export class QuickImportService {
try { try {
console.log('[QuickImport] Hämtar HTML från:', url); console.log('[QuickImport] Hämtar HTML från:', url);
// Hämta HTML från URL
const response = await fetch(url, { const response = await fetch(url, {
headers: { headers: {
'User-Agent': 'User-Agent':
@@ -93,7 +276,6 @@ export class QuickImportService {
const html = await response.text(); const html = await response.text();
console.log('[QuickImport] HTML längd:', html.length, 'tecken'); console.log('[QuickImport] HTML längd:', html.length, 'tecken');
// Välj lämplig parser
const parsers: RecipeParser[] = [ const parsers: RecipeParser[] = [
new IcaRecipeParser(), new IcaRecipeParser(),
new GenericRecipeParser(), new GenericRecipeParser(),
@@ -121,12 +303,10 @@ export class QuickImportService {
throw new Error('Kunde inte hitta receptnamn på sidan. Försök med en annan länk.'); throw new Error('Kunde inte hitta receptnamn på sidan. Försök med en annan länk.');
} }
// Konvertera till Markdown-format
const markdown = this.recipeToMarkdown(recipe, url); const markdown = this.recipeToMarkdown(recipe, url);
console.log('[QuickImport] Markdown genererad, längd:', markdown.length); console.log('[QuickImport] Markdown genererad, längd:', markdown.length);
// Detektera källa från URL let source: 'ica' | 'pdf' | 'image' | 'other' = 'other';
let source: 'ica' | 'pdf' | 'other' = 'other';
if (/ica\.se/i.test(url)) { if (/ica\.se/i.test(url)) {
source = 'ica'; source = 'ica';
} }
@@ -163,17 +343,14 @@ export class QuickImportService {
): string { ): string {
const lines: string[] = []; const lines: string[] = [];
// Titel
lines.push(`# ${recipe.name}`); lines.push(`# ${recipe.name}`);
lines.push(''); lines.push('');
// Beskrivning
if (recipe.description) { if (recipe.description) {
lines.push(recipe.description); lines.push(recipe.description);
lines.push(''); lines.push('');
} }
// Ingredienser
if (recipe.ingredients.length > 0) { if (recipe.ingredients.length > 0) {
lines.push('## Ingredienser'); lines.push('## Ingredienser');
for (const ing of recipe.ingredients) { for (const ing of recipe.ingredients) {
@@ -185,14 +362,12 @@ export class QuickImportService {
lines.push(''); lines.push('');
} }
// Instruktioner
if (recipe.instructions) { if (recipe.instructions) {
lines.push('## Tillvägagångssätt'); lines.push('## Tillvägagångssätt');
lines.push(recipe.instructions); lines.push(recipe.instructions);
lines.push(''); lines.push('');
} }
// Källa
if (sourceUrl) { if (sourceUrl) {
lines.push('---'); lines.push('---');
lines.push(''); lines.push('');
+17 -33
View File
@@ -2,48 +2,32 @@ import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
console.log('[QuickImportProxy] Mottog POST-anrop'); const contentType = request.headers.get('content-type') ?? '';
const { input } = await request.json(); const isMultipart = contentType.includes('multipart/form-data');
console.log('[QuickImportProxy] Input från request:', input); const backendUrl = process.env.BACKEND_URL || process.env.NEXT_PUBLIC_API_URL || 'http://recipe-api:8080';
if (!input || typeof input !== 'string') {
console.log('[QuickImportProxy] Validering misslyckades');
return NextResponse.json(
{ error: 'Du måste ange en URL eller filsökväg' },
{ status: 400 }
);
}
// Anropa backend
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://recipe-api:8080';
console.log('[QuickImportProxy] Anropar backend på:', backendUrl + '/api/quick-import');
const response = await fetch(`${backendUrl}/api/quick-import`, { const response = await fetch(`${backendUrl}/api/quick-import`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, body: isMultipart
body: JSON.stringify({ input: input.trim() }), ? await request.formData()
: JSON.stringify(await request.json()),
headers: isMultipart ? undefined : { 'Content-Type': 'application/json' },
cache: 'no-store',
}); });
console.log('[QuickImportProxy] Backend svar status:', response.status); const text = await response.text();
if (!response.ok) { return new NextResponse(text, {
console.log('[QuickImportProxy] Backend returnerade error'); status: response.status,
const errorData = await response.json().catch(() => ({})); headers: {
console.log('[QuickImportProxy] Error data:', errorData); 'Content-Type': response.headers.get('content-type') ?? 'application/json',
return NextResponse.json( },
{ error: errorData.message || 'Importen misslyckades' }, });
{ status: response.status }
);
}
const data = await response.json();
console.log('[QuickImportProxy] Framgång! Markdown längd:', data.markdown?.length);
return NextResponse.json(data);
} catch (error) { } catch (error) {
console.error('[QuickImportProxy] EXCEPTION:', error); console.error('[QuickImportProxy] EXCEPTION:', error);
return NextResponse.json( return NextResponse.json(
{ error: 'Serverfelet vid import. Försök igen senare.' }, { message: 'Kunde inte nå importtjänsten.' },
{ status: 500 } { status: 503 },
); );
} }
} }
+3
View File
@@ -16,6 +16,9 @@ export default function HomePage() {
<Link href="/recipes" style={{ padding: '0.5rem', background: '#eee', borderRadius: '4px', textDecoration: 'none', color: '#222' }}> <Link href="/recipes" style={{ padding: '0.5rem', background: '#eee', borderRadius: '4px', textDecoration: 'none', color: '#222' }}>
till recept till recept
</Link> </Link>
<Link href="/recipes/import" style={{ padding: '0.5rem', background: '#eee', borderRadius: '4px', textDecoration: 'none', color: '#222' }}>
Importera recept från PDF eller bild
</Link>
</div> </div>
</main> </main>
); );
+111 -119
View File
@@ -1,43 +1,85 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState } from 'react'; import { useState } from 'react';
import Navigation from '../../Navigation'; import Navigation from '../../Navigation';
import { parseErrorResponse } from '../../../lib/error-handler';
export default function ImportFilePage() { export default function ImportFilePage() {
const [selectedMethod, setSelectedMethod] = useState<'file' | 'url' | null>(null); const router = useRouter();
const [uploadProgress, setUploadProgress] = useState(0); const [selectedMethod, setSelectedMethod] = useState<'file' | 'url' | null>('file');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [url, setUrl] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleFileSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setError(null);
setUploadProgress(0);
// Placeholder för filuppladdning
// I framtiden kan detta hanteras med backend-endpoint för PDF-parsing
if (file.type === 'application/pdf') {
setError('PDF-import är under utveckling. Använd "Skriv in recept" för att mata in recept manuellt.');
} else {
setError('Endast PDF-filer stöds för närvarande.');
}
setUploadProgress(0);
};
const handleURLSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
const formData = new FormData(e.currentTarget);
const url = formData.get('url') as string;
if (!url) { if (!selectedFile) {
setError('Vänligen ange en URL'); setError('Välj en PDF eller bildfil först.');
return; return;
} }
setError('Länk-import är under utveckling. Använd "Skriv in recept" för att mata in recept manuellt.'); setError(null);
setIsLoading(true);
try {
const formData = new FormData();
formData.append('file', selectedFile);
const res = await fetch('/api/quick-import-proxy', {
method: 'POST',
body: formData,
});
if (!res.ok) {
const errorMessage = await parseErrorResponse(res);
throw new Error(errorMessage);
}
const data = await res.json();
sessionStorage.setItem('prefilled_markdown', data.markdown ?? '');
router.push('/recipes/write');
} catch (err) {
setError(err instanceof Error ? err.message : 'Importen misslyckades.');
} finally {
setIsLoading(false);
}
};
const handleUrlSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!url.trim()) {
setError('Vänligen ange en URL.');
return;
}
setError(null);
setIsLoading(true);
try {
const res = await fetch('/api/quick-import-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: url.trim() }),
});
if (!res.ok) {
const errorMessage = await parseErrorResponse(res);
throw new Error(errorMessage);
}
const data = await res.json();
sessionStorage.setItem('prefilled_markdown', data.markdown ?? '');
router.push('/recipes/write');
} catch (err) {
setError(err instanceof Error ? err.message : 'Importen misslyckades.');
} finally {
setIsLoading(false);
}
}; };
return ( return (
@@ -45,7 +87,7 @@ export default function ImportFilePage() {
<Navigation /> <Navigation />
<h1 style={{ marginBottom: '0.5rem' }}>Importera från fil eller länk</h1> <h1 style={{ marginBottom: '0.5rem' }}>Importera från fil eller länk</h1>
<p style={{ color: '#666', marginBottom: '1.5rem' }}> <p style={{ color: '#666', marginBottom: '1.5rem' }}>
Ladda upp en receptfil (PDF) eller ange en URL för att importera ett recept. Ladda upp en PDF eller bild för OCR, eller ange en receptlänk.
</p> </p>
{error && ( {error && (
@@ -60,7 +102,7 @@ export default function ImportFilePage() {
fontSize: '0.95rem', fontSize: '0.95rem',
}} }}
> >
{error} {error}
</div> </div>
)} )}
@@ -72,7 +114,6 @@ export default function ImportFilePage() {
marginBottom: '2rem', marginBottom: '2rem',
}} }}
> >
{/* Fil-upload */}
<div <div
onClick={() => setSelectedMethod('file')} onClick={() => setSelectedMethod('file')}
style={{ style={{
@@ -81,84 +122,48 @@ export default function ImportFilePage() {
borderRadius: '8px', borderRadius: '8px',
background: selectedMethod === 'file' ? '#f0f9ff' : '#f9fafb', background: selectedMethod === 'file' ? '#f0f9ff' : '#f9fafb',
cursor: 'pointer', cursor: 'pointer',
transition: 'all 0.2s',
}} }}
> >
<h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#0070f3' }}> <h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#0070f3' }}>
📄 Ladda upp fil Ladda upp PDF eller bild
</h2> </h2>
<p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}> <p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}>
Ladda upp ett recept från en PDF eller textfil Stöd för PDF, PNG, JPG, JPEG, WEBP och BMP.
</p> </p>
{selectedMethod === 'file' && ( {selectedMethod === 'file' && (
<div style={{ marginTop: '1rem' }}> <form onSubmit={handleFileSubmit} style={{ display: 'grid', gap: '0.75rem' }}>
<label
style={{
display: 'block',
padding: '1rem',
background: 'white',
border: '2px dashed #0070f3',
borderRadius: '6px',
textAlign: 'center',
cursor: 'pointer',
transition: 'all 0.2s',
}}
onDragOver={(e) => {
e.preventDefault();
(e.currentTarget as HTMLElement).style.background = '#e3f2fd';
}}
onDragLeave={(e) => {
(e.currentTarget as HTMLElement).style.background = 'white';
}}
>
<input <input
type="file" type="file"
accept=".pdf,.txt,.docx" accept=".pdf,.png,.jpg,.jpeg,.webp,.bmp"
onChange={handleFileUpload} onChange={(e) => setSelectedFile(e.target.files?.[0] ?? null)}
style={{ display: 'none' }}
/>
<p style={{ margin: '0', color: '#0070f3', fontWeight: 600 }}>
Dra och släpp fil här
</p>
<p style={{ margin: '0.5rem 0 0 0', color: '#999', fontSize: '0.85rem' }}>
eller klicka för att välja
</p>
<p style={{ margin: '0.5rem 0 0 0', color: '#999', fontSize: '0.8rem' }}>
PDF, TXT, DOCX stöds
</p>
</label>
{uploadProgress > 0 && uploadProgress < 100 && (
<div style={{ marginTop: '0.75rem' }}>
<div
style={{ style={{
width: '100%', padding: '0.75rem',
height: '6px', background: 'white',
background: '#e5e7eb', border: '1px solid #cbd5e1',
borderRadius: '3px', borderRadius: '6px',
overflow: 'hidden', }}
/>
<button
type="submit"
disabled={!selectedFile || isLoading}
style={{
padding: '0.75rem',
background: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: !selectedFile || isLoading ? 'not-allowed' : 'pointer',
opacity: !selectedFile || isLoading ? 0.6 : 1,
fontWeight: 600,
}} }}
> >
<div {isLoading ? 'Importerar...' : 'Importera fil'}
style={{ </button>
height: '100%', </form>
background: '#0070f3',
width: `${uploadProgress}%`,
transition: 'width 0.3s',
}}
/>
</div>
<p style={{ margin: '0.5rem 0 0 0', fontSize: '0.85rem', color: '#666' }}>
{uploadProgress}%
</p>
</div>
)}
</div>
)} )}
</div> </div>
{/* URL-import */}
<div <div
onClick={() => setSelectedMethod('url')} onClick={() => setSelectedMethod('url')}
style={{ style={{
@@ -167,21 +172,21 @@ export default function ImportFilePage() {
borderRadius: '8px', borderRadius: '8px',
background: selectedMethod === 'url' ? '#f0fdf4' : '#f9fafb', background: selectedMethod === 'url' ? '#f0fdf4' : '#f9fafb',
cursor: 'pointer', cursor: 'pointer',
transition: 'all 0.2s',
}} }}
> >
<h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#10b981' }}> <h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#10b981' }}>
🔗 Länk till recept Länk till recept
</h2> </h2>
<p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}> <p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}>
Ange URL till en receptsida eller blogg Ange URL till exempelvis ICA eller en annan receptsida.
</p> </p>
{selectedMethod === 'url' && ( {selectedMethod === 'url' && (
<form onSubmit={handleURLSubmit} style={{ marginTop: '1rem' }}> <form onSubmit={handleUrlSubmit} style={{ display: 'grid', gap: '0.75rem' }}>
<input <input
type="url" type="url"
name="url" value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://exempel.se/recept/..." placeholder="https://exempel.se/recept/..."
style={{ style={{
width: '100%', width: '100%',
@@ -190,11 +195,11 @@ export default function ImportFilePage() {
borderRadius: '6px', borderRadius: '6px',
fontSize: '0.9rem', fontSize: '0.9rem',
boxSizing: 'border-box', boxSizing: 'border-box',
marginBottom: '0.75rem',
}} }}
/> />
<button <button
type="submit" type="submit"
disabled={!url.trim() || isLoading}
style={{ style={{
width: '100%', width: '100%',
padding: '0.75rem', padding: '0.75rem',
@@ -202,41 +207,33 @@ export default function ImportFilePage() {
color: 'white', color: 'white',
border: 'none', border: 'none',
borderRadius: '4px', borderRadius: '4px',
cursor: 'pointer', cursor: !url.trim() || isLoading ? 'not-allowed' : 'pointer',
fontWeight: 500, opacity: !url.trim() || isLoading ? 0.6 : 1,
fontWeight: 600,
fontSize: '0.95rem', fontSize: '0.95rem',
}} }}
> >
Importera från länk {isLoading ? 'Importerar...' : 'Importera från länk'}
</button> </button>
</form> </form>
)} )}
</div> </div>
</div> </div>
{/* Info-box */}
<div <div
style={{ style={{
background: '#fef3c7', background: '#f0fdf4',
border: '1px solid #fcd34d', border: '1px solid #86efac',
borderRadius: '6px', borderRadius: '6px',
padding: '1rem', padding: '1rem',
marginBottom: '1.5rem', marginBottom: '1.5rem',
color: '#92400e', color: '#166534',
fontSize: '0.9rem', fontSize: '0.9rem',
}} }}
> >
<strong>💡 Tips:</strong> För närvarande är PDF och länk-import under utveckling. Du kan{' '} Efter import öppnas receptet automatiskt i redigeringsläget.
<Link
href="/recipes/write"
style={{ color: '#0070f3', textDecoration: 'none', fontWeight: 600 }}
>
skriv in receptet manuellt
</Link>{' '}
eller prova att ladda upp en fil och se om det fungerar.
</div> </div>
{/* Knapp för att gå tillbaka */}
<div style={{ display: 'flex', gap: '1rem' }}> <div style={{ display: 'flex', gap: '1rem' }}>
<Link <Link
href="/recipes/create" href="/recipes/create"
@@ -245,14 +242,12 @@ export default function ImportFilePage() {
background: 'transparent', background: 'transparent',
border: '1px solid #ddd', border: '1px solid #ddd',
borderRadius: '4px', borderRadius: '4px',
cursor: 'pointer',
fontSize: '1rem',
textDecoration: 'none', textDecoration: 'none',
color: '#333', color: '#333',
fontWeight: 500, fontWeight: 500,
}} }}
> >
Tillbaka Tillbaka
</Link> </Link>
<Link <Link
href="/recipes/write" href="/recipes/write"
@@ -260,11 +255,8 @@ export default function ImportFilePage() {
padding: '0.75rem 1.5rem', padding: '0.75rem 1.5rem',
background: '#0070f3', background: '#0070f3',
color: 'white', color: 'white',
border: 'none',
borderRadius: '4px', borderRadius: '4px',
textDecoration: 'none', textDecoration: 'none',
cursor: 'pointer',
fontSize: '1rem',
fontWeight: 500, fontWeight: 500,
}} }}
> >