translate to english

This commit is contained in:
Andreas Knuth 2025-01-15 00:05:57 +00:00
parent 156d017730
commit f968f2ab38
14 changed files with 330 additions and 320 deletions

View File

@ -8,16 +8,16 @@ import { DeckListComponent } from './deck-list.component';
selector: 'app-root',
template: `
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold text-center mb-8">Vokabeltraining</h1>
<h1 class="text-3xl font-bold text-center mb-8">Vocabulary Training</h1>
<app-deck-list></app-deck-list>
</div>
`,
standalone: true,
imports: [ CommonModule, DeckListComponent]
imports: [CommonModule, DeckListComponent]
})
export class AppComponent {
title = 'vokabeltraining';
title = 'vocabulary-training';
ngOnInit(): void {
initFlowbite();
}
}
}

View File

@ -1,4 +1,3 @@
<!-- src/app/create-deck-modal.component.html -->
<div #createDeckModal id="createDeckModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
<div class="relative w-full h-full max-w-md md:h-auto">
<div class="relative bg-white rounded-lg shadow">
@ -6,17 +5,17 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Schließen</span>
<span class="sr-only">Close</span>
</button>
<div class="p-6">
<h3 class="mb-4 text-xl font-medium text-gray-900">Neues Deck erstellen</h3>
<h3 class="mb-4 text-xl font-medium text-gray-900">Create New Deck</h3>
<form (submit)="createDeck($event)">
<div class="mb-4">
<label for="deckName" class="block text-sm font-medium text-gray-700">Deck-Name</label>
<label for="deckName" class="block text-sm font-medium text-gray-700">Deck Name</label>
<input type="text" id="deckName" [(ngModel)]="deckName" name="deckName" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" />
</div>
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Erstellen
Create
</button>
</form>
</div>

View File

@ -1,4 +1,3 @@
// src/app/create-deck-modal.component.ts
import { Component, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { DeckService } from '../deck.service';
import { CommonModule } from '@angular/common';
@ -30,7 +29,7 @@ export class CreateDeckModalComponent implements AfterViewInit {
createDeck(event: Event): void {
event.preventDefault();
if (this.deckName.trim() === '') {
alert('Bitte einen Deck-Namen eingeben.');
alert('Please enter a deck name.');
return;
}
@ -41,8 +40,8 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.modal.hide();
},
error: (err) => {
console.error('Fehler beim Erstellen des Decks', err);
alert('Fehler beim Erstellen des Decks.');
console.error('Error creating deck', err);
alert('Error creating deck.');
}
});
}
@ -50,5 +49,4 @@ export class CreateDeckModalComponent implements AfterViewInit {
closeModal(): void {
this.modal.hide();
}
}
}

View File

@ -1,22 +1,21 @@
<!-- src/app/deck-list.component.html -->
<div>
<!-- Button zum Erstellen eines neuen Decks -->
<!-- Button to create a new deck -->
<div class="flex justify-end mb-4">
<button (click)="openCreateDeckModal()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Neues Deck erstellen
Create New Deck
</button>
</div>
<!-- Decks anzeigen -->
<!-- Display decks -->
<div class="flex flex-wrap">
<div *ngFor="let deck of decks" class="bg-white shadow rounded-lg p-6 w-full md:w-1/2 lg:w-1/3 flex flex-col border-dashed border-2 border-indigo-600">
<!-- Deck-Header mit Toggle-Button -->
<!-- Deck header with toggle button -->
<div class="flex justify-between items-center mb-4">
<div class="flex items-center space-x-2">
<h2 class="text-xl font-semibold">{{ deck.name }}</h2>
<span class="text-gray-600">({{ deck.images.length }} Bilder)</span>
<span class="text-gray-600">({{ deck.images.length }} images)</span>
</div>
<button (click)="toggleDeckExpansion(deck.name)" class="text-gray-500 hover:text-gray-700 focus:outline-none" title="Deck ein-/ausklappen">
<button (click)="toggleDeckExpansion(deck.name)" class="text-gray-500 hover:text-gray-700 focus:outline-none" title="Expand/Collapse Deck">
<svg *ngIf="!isDeckExpanded(deck.name)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-0 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
@ -26,54 +25,54 @@
</button>
</div>
<!-- Bildliste und Action-Buttons nur anzeigen, wenn das Deck erweitert ist und kein Training aktiv ist -->
<!-- Image list and action buttons only shown if the deck is expanded and no training is active -->
<ng-container *ngIf="isDeckExpanded(deck.name) && !selectedDeck">
<!-- Liste der Bilder mit Anzahl der Boxen und Icons -->
<!-- List of images with number of boxes and icons -->
<ul class="mb-4">
<li *ngFor="let image of deck.images" class="flex justify-between items-center py-2 border-b last:border-b-0">
<div class="flex items-center space-x-2">
<div class="relative group">
<!-- Tooltip Inhalt (Bild) -->
<!-- Tooltip content (image) -->
<div class="absolute left-0 bottom-full mb-2 w-48 bg-white border border-gray-300 rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 z-10 pointer-events-none">
<img src="/api/debug_image/{{image.id}}/thumbnail.jpg" alt="{{ image.name }}" class="w-full h-auto object-cover">
</div>
<!-- Bildname mit Tooltip -->
<!-- Image name with tooltip -->
<span class="font-medium cursor-pointer">
{{ image.name }}
</span>
</div>
<span class="text-gray-600">({{ image.boxes.length }} Boxen)</span>
<span class="text-gray-600">({{ image.boxes.length }} boxes)</span>
</div>
<div class="flex space-x-2">
<!-- Edit Icon -->
<button (click)="editImage(deck, image)" class="text-blue-500 hover:text-blue-700" title="Bild bearbeiten">
<button (click)="editImage(deck, image)" class="text-blue-500 hover:text-blue-700" title="Edit Image">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 4H4v7m0 0l9-9 9 9M20 13v7h-7m0 0l-9-9-9 9" />
</svg>
</button>
<!-- Delete Icon -->
<button (click)="deleteImage(deck, image)" class="text-red-500 hover:text-red-700" title="Bild löschen">
<button (click)="deleteImage(deck, image)" class="text-red-500 hover:text-red-700" title="Delete Image">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- Move Icon -->
<button (click)="openMoveImageModal(deck, image)" class="text-yellow-500 hover:text-yellow-700" title="Bild verschieben">
<button (click)="openMoveImageModal(deck, image)" class="text-yellow-500 hover:text-yellow-700" title="Move Image">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</button>
</button>
</div>
</li>
</ul>
<!-- Action-Buttons -->
<!-- Action buttons -->
<div class="flex space-x-2">
<button (click)="openTraining(deck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Training starten
Start Training
</button>
<button (click)="openUploadImageModal(deck.name)" class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Bild hinzufügen
Add Image
</button>
</div>
</ng-container>
@ -84,18 +83,17 @@
<app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal>
<!-- UploadImageModalComponent -->
<!-- <app-upload-image-modal [deckName]="currentUploadDeckName" (imageUploaded)="loadDecks()"></app-upload-image-modal> -->
<app-upload-image-modal (imageUploaded)="onImageUploaded($event)"> </app-upload-image-modal>
<app-upload-image-modal (imageUploaded)="onImageUploaded($event)"></app-upload-image-modal>
<app-edit-image-modal *ngIf="imageData" [deckName]="currentUploadDeckName" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
<!-- TrainingComponent -->
<app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training>
<!-- MoveImageModalComponent -->
<app-move-image-modal
*ngIf="imageToMove"
[image]="imageToMove.image"
[sourceDeck]="imageToMove.sourceDeck"
[decks]="decks"
(moveCompleted)="onImageMoved()"
<!-- MoveImageModalComponent -->
<app-move-image-modal
*ngIf="imageToMove"
[image]="imageToMove.image"
[sourceDeck]="imageToMove.sourceDeck"
[decks]="decks"
(moveCompleted)="onImageMoved()"
(closed)="imageToMove = null">
</app-move-image-modal>
</div>
</div>

View File

@ -1,4 +1,3 @@
// src/app/deck-list.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { DeckService, Deck, DeckImage } from './deck.service';
import { CommonModule } from '@angular/common';
@ -19,7 +18,7 @@ import { MoveImageModalComponent } from './move-image-modal/move-image-modal.com
UploadImageModalComponent,
TrainingComponent,
EditImageModalComponent,
MoveImageModalComponent, // Hinzufügen der neuen Komponente
MoveImageModalComponent, // Adding the new component
UploadImageModalComponent
]
})
@ -36,10 +35,10 @@ export class DeckListComponent implements OnInit {
currentUploadDeckName: string = '';
// Set zur Verfolgung erweiterter Decks
// Set to track expanded decks
expandedDecks: Set<string> = new Set<string>();
// State für das Verschieben von Bildern
// State for moving images
imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null;
constructor(private deckService: DeckService) { }
@ -52,56 +51,56 @@ export class DeckListComponent implements OnInit {
loadDecks(): void {
this.deckService.getDecks().subscribe({
next: (data) => this.decks = data,
error: (err) => console.error('Fehler beim Laden der Decks', err)
error: (err) => console.error('Error loading decks', err)
});
}
deleteDeck(deckName: string): void {
if (!confirm(`Bist du sicher, dass du das Deck "${deckName}" löschen möchtest?`)) {
if (!confirm(`Are you sure you want to delete the deck "${deckName}"?`)) {
return;
}
this.deckService.deleteDeck(deckName).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Decks', err)
error: (err) => console.error('Error deleting deck', err)
});
}
deleteImage(deck: Deck, image: DeckImage): void {
if (!confirm(`Bist du sicher, dass du das Bild "${image.name}" löschen möchtest?`)) {
if (!confirm(`Are you sure you want to delete the image "${image.name}"?`)) {
return;
}
const imageId = image.id;
const imageId = image.id;
this.deckService.deleteImage(imageId).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Bildes', err)
error: (err) => console.error('Error deleting image', err)
});
}
editImage(deck: Deck, image: DeckImage): void {
let imageSrc = null
let imageSrc = null;
this.currentUploadDeckName = deck.name;
fetch(`/api/debug_image/${image.id}/original_compressed.jpg`)
.then(response => {
if (!response.ok) {
throw new Error('Netzwerkantwort war nicht ok');
}
return response.blob();
})
.then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
imageSrc = reader.result; // Base64-String
this.imageData = { imageSrc, deckImage: image }
};
reader.readAsDataURL(blob);
})
.catch(error => {
console.error('Fehler beim Laden des Bildes:', error);
});
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob();
})
.then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
imageSrc = reader.result; // Base64 string
this.imageData = { imageSrc, deckImage: image };
};
reader.readAsDataURL(blob);
})
.catch(error => {
console.error('Error loading image:', error);
});
}
openTraining(deck: Deck): void {
this.selectedDeck = deck;
}
@ -121,7 +120,7 @@ export class DeckListComponent implements OnInit {
this.uploadImageModal.open();
}
// Methode zum Umschalten der Deck-Erweiterung
// Method to toggle deck expansion
toggleDeckExpansion(deckName: string): void {
if (this.expandedDecks.has(deckName)) {
this.expandedDecks.delete(deckName);
@ -131,12 +130,12 @@ export class DeckListComponent implements OnInit {
this.saveExpandedDecks();
}
// Methode zur Überprüfung, ob ein Deck erweitert ist
// Method to check if a deck is expanded
isDeckExpanded(deckName: string): boolean {
return this.expandedDecks.has(deckName);
}
// Laden der erweiterten Decks aus dem sessionStorage
// Load expanded decks from sessionStorage
loadExpandedDecks(): void {
const stored = sessionStorage.getItem('expandedDecks');
if (stored) {
@ -144,48 +143,48 @@ export class DeckListComponent implements OnInit {
const parsed: string[] = JSON.parse(stored);
this.expandedDecks = new Set<string>(parsed);
} catch (e) {
console.error('Fehler beim Parsen der erweiterten Decks aus sessionStorage', e);
console.error('Error parsing expanded decks from sessionStorage', e);
}
} else {
// Wenn keine Daten gespeichert sind, alle Decks standardmäßig nicht erweitern
// If no data is stored, do not expand any decks by default
this.expandedDecks = new Set<string>();
}
}
// Speichern der erweiterten Decks in das sessionStorage
// Save expanded decks to sessionStorage
saveExpandedDecks(): void {
const expandedArray = Array.from(this.expandedDecks);
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray));
}
// Funktion zum Öffnen des Upload Modals (kann durch einen Button ausgelöst werden)
// Function to open the upload modal (can be triggered by a button)
openUploadModal(): void {
this.uploadImageModal.open();
}
// Handler für das imageUploaded Event
// Handler for the imageUploaded event
onImageUploaded(imageData: any): void {
this.imageData = imageData;
}
onClosed(){
onClosed() {
this.imageData = null;
}
async onImageSaved() {
// Handle das Speichern der Bilddaten, z.B. aktualisiere die Liste der Bilder
// Handle saving the image data, e.g., update the list of images
this.imageData = null;
this.decks = await firstValueFrom(this.deckService.getDecks())
this.decks = await firstValueFrom(this.deckService.getDecks());
}
// Methode zum Öffnen des MoveImageModal
// Method to open the MoveImageModal
openMoveImageModal(deck: Deck, image: DeckImage): void {
this.imageToMove = { image, sourceDeck: deck };
}
// Handler für das moveCompleted Event
// Handler for the moveCompleted event
onImageMoved(): void {
this.imageToMove = null;
this.loadDecks();
}
}
}

View File

@ -1,4 +1,3 @@
// src/app/deck.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, Observable, switchMap } from 'rxjs';
@ -11,21 +10,21 @@ export interface Deck {
export interface DeckImage {
boxes: Box[];
name: string;
id:string;
id: string;
}
export interface Box {
id?:number;
x1:number;
x2:number;
y1:number;
y2:number;
id?: number;
x1: number;
x2: number;
y1: number;
y2: number;
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?:boolean;
isGraduated?: boolean;
}
export interface BackendBox {
@ -39,13 +38,13 @@ export interface BackendBox {
y2: number;
}
// Definiert ein einzelnes Punktpaar [x, y]
// Defines a single point pair [x, y]
type OcrPoint = [number, number];
// Definiert die Box als Array von vier Punkten
// Defines the box as an array of four points
type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint];
// Interface für jedes JSON-Objekt
// Interface for each JSON object
export interface OcrResult {
box: OcrBox;
confidence: number;
@ -69,6 +68,7 @@ export class DeckService {
})))
);
}
private groupImagesByName(images: any[]): DeckImage[] {
const imageMap: { [key: string]: DeckImage } = {};
@ -76,7 +76,7 @@ export class DeckService {
if (!imageMap[image.id]) {
imageMap[image.id] = {
name: image.name,
id:image.id,
id: image.id,
boxes: []
};
}
@ -87,17 +87,18 @@ export class DeckService {
y1: image.y1,
y2: image.y2,
due: image.due,
ivl:image.ivl,
factor:image.factor,
reps:image.reps,
lapses:image.lapses,
isGraduated:image.isGraduated?true:false
ivl: image.ivl,
factor: image.factor,
reps: image.reps,
lapses: image.lapses,
isGraduated: image.isGraduated ? true : false
});
});
return Object.values(imageMap);
}
getDeck(deckname:string): Observable<Deck> {
getDeck(deckname: string): Observable<Deck> {
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
}
@ -109,16 +110,16 @@ export class DeckService {
return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`);
}
saveImageData(data:any): Observable<any> {
saveImageData(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/image`, data);
}
// Neue Methode zum Löschen eines Bildes
// New method to delete an image
deleteImage(imageName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/image/${imageName}`);
}
// Neue Methode zum Verschieben eines Bildes
// New method to move an image
moveImage(imageId: string, targetDeckId: number): Observable<any> {
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId });
}
@ -126,4 +127,4 @@ export class DeckService {
updateBox(box: Box): Observable<any> {
return this.http.put(`${this.apiUrl}/boxes/${box.id}`, box);
}
}
}

View File

@ -1,4 +1,3 @@
<!-- src/app/edit-image-modal.component.html -->
<div #editImageModal id="editImageModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
<div class="relative h-full contents">
<div class="relative bg-white rounded-lg shadow">
@ -6,12 +5,12 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Schließen</span>
<span class="sr-only">Close</span>
</button>
<div class="p-6 relative">
<!-- Überschrift mit Boxanzahl -->
<!-- Header with box count -->
<h3 class="mb-4 text-xl font-medium text-gray-900">
Bild bearbeiten <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'en' : '' }})</span>
Edit Image <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'es' : '' }})</span>
</h3>
<!-- Canvas -->
@ -19,16 +18,16 @@
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
</div>
<!-- Buttons unter dem Canvas -->
<!-- Buttons below the canvas -->
<div class="mt-4 flex justify-between">
<button (click)="save()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Save
</button>
<button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Neue Box
New Box
</button>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -12,11 +12,11 @@ import { DeckImage, DeckService, OcrResult } from '../deck.service';
imports: [CommonModule]
})
export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// Konstante für die Boxfarbe
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Rot mit Transparenz
// Constant for box color
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Red with transparency
@Input() deckName: string = '';
@Input() imageData : {imageSrc:string|ArrayBuffer|null, deckImage:DeckImage|null} = {imageSrc:null,deckImage:null};
@Input() imageData: { imageSrc: string | ArrayBuffer | null, deckImage: DeckImage | null } = { imageSrc: null, deckImage: null };
@Output() imageSaved = new EventEmitter<void>();
@Output() closed = new EventEmitter<void>();
@ViewChild('editImageModal') modalElement!: ElementRef;
@ -35,11 +35,11 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
constructor(private deckService: DeckService) { }
async ngAfterViewInit() {
this.modal = new Modal(this.modalElement.nativeElement,{
this.modal = new Modal(this.modalElement.nativeElement, {
onHide: () => {
this.closed.emit();
}},
);
}
});
this.maxCanvasWidth = window.innerWidth * 0.6;
this.maxCanvasHeight = window.innerHeight * 0.6;
@ -89,13 +89,13 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
async processImage(): Promise<void> {
try {
if (!this.imageData){
if (!this.imageData) {
return;
}
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
// Hintergrundbild setzen
// Set background image
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
const originalWidth = backgroundImage.width!;
@ -120,7 +120,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.boxes = [];
// Boxen hinzufügen
// Add boxes
this.imageData.deckImage?.boxes.forEach(box => {
const rect = new fabric.Rect({
@ -128,7 +128,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: box.y1 * scaleFactor,
width: (box.x2 - box.x1) * scaleFactor,
height: (box.y2 - box.y1) * scaleFactor,
fill: this.BOX_COLOR, // Verwendung der Konstante
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
@ -159,7 +159,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// this.detectedText = ocrResults.map(result => result.text).join('\n');
} catch (error) {
console.error('Fehler bei der Bildverarbeitung:', error);
console.error('Error processing image:', error);
}
}
@ -221,7 +221,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: (canvasHeight - boxHeight) / 2,
width: boxWidth,
height: boxHeight,
fill: this.BOX_COLOR, // Verwendung der Konstante
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
@ -252,8 +252,8 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
}
save(): void {
// Hier implementierst du die Logik zum Speichern der Bilddaten
// Zum Beispiel über einen Service oder direkt hier
// Implement the logic to save the image data here
// For example, via a service or directly here
const data = {
deckname: this.deckName,
bildname: this.imageData.deckImage?.name, // this.imageFile?.name,
@ -266,10 +266,10 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.closeModal();
},
error: (err) => {
console.error('Fehler beim Speichern des Bildes:', err);
alert('Fehler beim Speichern des Bildes.');
console.error('Error saving image:', err);
alert('Error saving image.');
this.closeModal();
}
});
}
}
}

View File

@ -1,24 +1,22 @@
<!-- src/app/move-image-modal.component.html -->
<div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
<div class="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Bild verschieben</h2>
<p class="mb-4">Wähle das Zieldeck für das Bild <strong>{{ image.name }}</strong> aus.</p>
<select [(ngModel)]="selectedDeckId" class="w-full p-2 border border-gray-300 rounded mb-4">
<option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
{{ deck.name }}
</option>
</select>
<div class="flex justify-end space-x-2">
<button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
Abbrechen
</button>
<button
(click)="moveImage()"
[disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Verschieben
</button>
</div>
<div class="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Move Image</h2>
<p class="mb-4">Select the target deck for the image <strong>{{ image.name }}</strong>.</p>
<select [(ngModel)]="selectedDeckId" class="w-full p-2 border border-gray-300 rounded mb-4">
<option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
{{ deck.name }}
</option>
</select>
<div class="flex justify-end space-x-2">
<button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
Cancel
</button>
<button
(click)="moveImage()"
[disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Move
</button>
</div>
</div>
</div>

View File

@ -1,7 +1,5 @@
// src/app/move-image-modal.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DeckImage, Deck, DeckService } from '../deck.service';
@ -33,8 +31,8 @@ export class MoveImageModalComponent {
this.close();
},
error: (err) => {
console.error('Fehler beim Verschieben des Bildes:', err);
alert('Fehler beim Verschieben des Bildes.');
console.error('Error moving image:', err);
alert('Error moving image.');
}
});
}
@ -42,4 +40,4 @@ export class MoveImageModalComponent {
close(): void {
this.closed.emit();
}
}
}

View File

@ -1,53 +1,52 @@
<!-- src/app/training.component.html -->
<div class="mt-10">
<h2 class="text-2xl font-bold mb-4">Training: {{ deck.name }}</h2>
<div class="bg-white shadow rounded-lg p-6 flex flex-col items-center">
<canvas #canvas class="mb-4 border max-h-[50vh]"></canvas>
<div class="flex space-x-4 mb-4">
<!-- Anzeigen Button -->
<!-- Show Button -->
<button
(click)="showText()"
class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600"
[disabled]="isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Anzeigen
Show
</button>
<!-- Nochmal Button -->
<!-- Again Button -->
<button
(click)="markAgain()"
class="bg-orange-500 disabled:bg-orange-200 text-white py-2 px-4 rounded hover:bg-orange-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Nochmal ({{ getNextInterval(currentBox, 'again') }})
Again ({{ getNextInterval(currentBox, 'again') }})
</button>
<!-- Gut Button -->
<!-- Good Button -->
<button
(click)="markGood()"
class="bg-blue-500 disabled:bg-blue-200 text-white py-2 px-4 rounded hover:bg-blue-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Gut ({{ getNextInterval(currentBox, 'good') }})
Good ({{ getNextInterval(currentBox, 'good') }})
</button>
<!-- Einfach Button -->
<!-- Easy Button -->
<button
(click)="markEasy()"
class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Einfach ({{ getNextInterval(currentBox, 'easy') }})
Easy ({{ getNextInterval(currentBox, 'easy') }})
</button>
<!-- Nächstes Bild Button -->
<!-- Next Image Button -->
<button
(click)="skipToNextImage()"
class="bg-yellow-500 disabled:bg-yellow-200 text-white py-2 px-4 rounded hover:bg-yellow-600"
[disabled]="currentImageIndex >= deck.images.length"
>
Nächstes Bild
Next Image
</button>
</div>
@ -57,7 +56,7 @@
(click)="closeTraining()"
class="mt-4 text-gray-500 hover:text-gray-700 underline"
>
Training beenden
End Training
</button>
</div>
</div>
</div>

View File

@ -1,4 +1,3 @@
// training.component.ts
import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Deck, DeckImage, DeckService, Box } from '../deck.service';
import { CommonModule } from '@angular/common';
@ -27,7 +26,7 @@ export class TrainingComponent implements OnInit {
@Input() deck!: Deck;
@Output() close = new EventEmitter<void>();
@ViewChild('canvas',{static : false}) canvasRef!: ElementRef<HTMLCanvasElement>;
@ViewChild('canvas', { static: false }) canvasRef!: ElementRef<HTMLCanvasElement>;
currentImageIndex: number = 0;
currentImageData: DeckImage | null = null;
@ -41,22 +40,22 @@ export class TrainingComponent implements OnInit {
constructor(private deckService: DeckService) { }
ngOnInit(): void {
// Initialisierung wurde in ngAfterViewInit durchgeführt
// Initialization was done in ngAfterViewInit
}
ngAfterViewInit(){
// Initialisiere das erste Bild und die dazugehörigen Boxen
ngAfterViewInit() {
// Initialize the first image and its boxes
if (this.deck && this.deck.images.length > 0) {
this.loadImage(this.currentImageIndex);
} else {
alert('Kein Deck oder keine Bilder vorhanden.');
alert('No deck or images available.');
this.close.emit();
}
}
/**
* Lädt das Bild basierend auf dem gegebenen Index und initialisiert die zu überprüfenden Boxen.
* @param imageIndex Index des zu ladenden Bildes im Deck
* Loads the image based on the given index and initializes the boxes to review.
* @param imageIndex Index of the image to load in the deck
*/
loadImage(imageIndex: number): void {
if (imageIndex >= this.deck.images.length) {
@ -65,13 +64,13 @@ export class TrainingComponent implements OnInit {
}
this.currentImageData = this.deck.images[imageIndex];
// Initialisiere die Boxen für die aktuelle Runde
// Initialize the boxes for the current round
this.initializeBoxesToReview();
}
/**
* Ermittelt alle fälligen Boxen für die aktuelle Runde, mischt sie und setzt den aktuellen Box-Index zurück.
* Wenn keine Boxen mehr zu überprüfen sind, wird zum nächsten Bild gewechselt.
* Determines all due boxes for the current round, shuffles them, and resets the current box index.
* If no boxes are left to review, it moves to the next image.
*/
initializeBoxesToReview(): void {
if (!this.currentImageData) {
@ -79,42 +78,42 @@ export class TrainingComponent implements OnInit {
return;
}
// Filtere alle Boxen, die fällig sind (due <= heute)
// Filter all boxes that are due (due <= today)
const today = this.getTodayInDays();
this.boxesToReview = this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today);
if (this.boxesToReview.length === 0) {
// Keine Boxen mehr für dieses Bild, wechsle zum nächsten Bild
// No more boxes for this image, move to the next image
this.nextImage();
return;
}
// Mische die Boxen zufällig
// Shuffle the boxes randomly
this.boxesToReview = this.shuffleArray(this.boxesToReview);
// Initialisiere den Array zur Verfolgung der enthüllten Boxen
// Initialize the array to track revealed boxes
this.boxRevealed = new Array(this.boxesToReview.length).fill(false);
// Setze den aktuellen Box-Index zurück
// Reset the current box index
this.currentBoxIndex = 0;
this.isShowingBox = false;
// Zeichne das Canvas neu
// Redraw the canvas
this.drawCanvas();
}
/**
* Gibt das heutige Datum in Tagen seit der UNIX-Epoche zurück.
* Returns today's date in days since the UNIX epoch.
*/
getTodayInDays(): number {
const epoch = new Date(1970, 0, 1); // Anki verwendet UNIX-Epoche
const epoch = new Date(1970, 0, 1); // Anki uses UNIX epoch
const today = new Date();
return Math.floor((today.getTime() - epoch.getTime()) / (1000 * 60 * 60 * 24));
}
/**
* Zeichnet das aktuelle Bild und die Boxen auf das Canvas.
* Boxen werden rot dargestellt, wenn sie verdeckt sind, und grün, wenn sie enthüllt sind.
* Draws the current image and boxes on the canvas.
* Boxes are displayed in red if hidden and green if revealed.
*/
drawCanvas(): void {
const canvas = this.canvasRef.nativeElement;
@ -124,27 +123,27 @@ export class TrainingComponent implements OnInit {
const img = new Image();
img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`;
img.onload = () => {
// Setze die Größe des Canvas auf die Größe des Bildes
// Set the canvas size to the image size
canvas.width = img.width;
canvas.height = img.height;
// Zeichne das Bild
// Draw the image
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Zeichne die Boxen
// Draw the boxes
this.boxesToReview.forEach((box, index) => {
ctx.beginPath();
ctx.rect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1);
if (this.currentBoxIndex === index && this.isShowingBox || (box.due && box.due-this.getTodayInDays()>0)) {
// Box ist aktuell enthüllt, keine Überlagerung
if (this.currentBoxIndex === index && this.isShowingBox || (box.due && box.due - this.getTodayInDays() > 0)) {
// Box is currently revealed, no overlay
return;
} else if (this.currentBoxIndex === index && !this.isShowingBox) {
// Box ist enthüllt
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Undurchsichtige grüne Überlagerung
// Box is revealed
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Opaque green overlay
} else {
// Box ist verdeckt
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Undurchsichtige rote Überlagerung
// Box is hidden
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Opaque red overlay
}
ctx.fill();
ctx.lineWidth = 2;
@ -154,27 +153,27 @@ export class TrainingComponent implements OnInit {
};
img.onerror = () => {
console.error('Fehler beim Laden des Bildes für Canvas.');
alert('Fehler beim Laden des Bildes für Canvas.');
console.error('Error loading image for canvas.');
alert('Error loading image for canvas.');
this.close.emit();
};
}
/**
* Mischt ein Array zufällig.
* @param array Das zu mischende Array
* @returns Das gemischte Array
* Shuffles an array randomly.
* @param array The array to shuffle
* @returns The shuffled array
*/
shuffleArray<T>(array: T[]): T[] {
let currentIndex = array.length, randomIndex;
// Solange noch Elemente zum Mischen vorhanden sind
// While there are elements to shuffle
while (currentIndex !== 0) {
// Wähle ein verbleibendes Element
// Pick a remaining element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// Tausche es mit dem aktuellen Element
// Swap it with the current element
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
@ -183,7 +182,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Gibt die aktuelle Box zurück, die überprüft wird.
* Returns the current box being reviewed.
*/
get currentBox(): Box | null {
if (this.currentBoxIndex < this.boxesToReview.length) {
@ -193,7 +192,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Zeigt den Inhalt der aktuellen Box an.
* Reveals the content of the current box.
*/
showText(): void {
if (this.currentBoxIndex >= this.boxesToReview.length) return;
@ -203,7 +202,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Nochmal" und fährt mit der nächsten Box fort.
* Marks the current box as "Again" and proceeds to the next box.
*/
async markAgain(): Promise<void> {
await this.updateCard('again');
@ -212,7 +211,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Gut" und fährt mit der nächsten Box fort.
* Marks the current box as "Good" and proceeds to the next box.
*/
async markGood(): Promise<void> {
await this.updateCard('good');
@ -221,7 +220,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Einfach" und fährt mit der nächsten Box fort.
* Marks the current box as "Easy" and proceeds to the next box.
*/
async markEasy(): Promise<void> {
await this.updateCard('easy');
@ -230,8 +229,8 @@ export class TrainingComponent implements OnInit {
}
/**
* Aktualisiert die SRS-Daten der aktuellen Box basierend auf der gegebenen Aktion.
* @param action Die durchgeführte Aktion ('again', 'good', 'easy')
* Updates the SRS data of the current box based on the given action.
* @param action The action performed ('again', 'good', 'easy')
*/
async updateCard(action: 'again' | 'good' | 'easy'): Promise<void> {
if (this.currentBoxIndex >= this.boxesToReview.length) return;
@ -239,96 +238,96 @@ export class TrainingComponent implements OnInit {
const box = this.boxesToReview[this.currentBoxIndex];
const today = this.getTodayInDays();
// Berechne das neue Intervall und eventuell den neuen Faktor
// Calculate the new interval and possibly the new factor
const { newIvl, newFactor, newReps, newLapses, newIsGraduated } = this.calculateNewInterval(box, action);
// Aktualisiere das Fälligkeitsdatum
const nextDue = today + Math.floor(newIvl/1440);
// Update the due date
const nextDue = today + Math.floor(newIvl / 1440);
// Aktualisiere das Box-Objekt
// Update the box object
box.ivl = newIvl;
box.factor = newFactor;
box.reps = newReps;
box.lapses = newLapses;
box.due = nextDue;
box.isGraduated = newIsGraduated
box.isGraduated = newIsGraduated;
// Sende das Update an das Backend
// Send the update to the backend
try {
await lastValueFrom(this.deckService.updateBox(box));
} catch (error) {
console.error('Fehler beim Aktualisieren der Box:', error);
alert('Fehler beim Aktualisieren der Box.');
console.error('Error updating box:', error);
alert('Error updating box.');
}
}
/**
* Berechnet das neue Intervall, den Faktor, die Wiederholungen und die Lapses basierend auf der Aktion.
* @param box Die aktuelle Box
* @param action Die Aktion ('again', 'good', 'easy')
* @returns Ein Objekt mit den neuen Werten für ivl, factor, reps und lapses
* Calculates the new interval, factor, repetitions, and lapses based on the action.
* @param box The current box
* @param action The action ('again', 'good', 'easy')
* @returns An object with the new values for ivl, factor, reps, and lapses
*/
calculateNewInterval(box: Box, action: 'again' | 'good' | 'easy'): { newIvl: number, newFactor: number, newReps: number, newLapses: number, newIsGraduated: boolean } {
let newIvl = box.ivl || 0;
let newFactor = box.factor || 2.5;
let newReps = box.reps || 0;
let newLapses = box.lapses || 0;
let newIsGraduated = box.isGraduated || false
let newIsGraduated = box.isGraduated || false;
if (action === 'again') {
newLapses++;
newReps = 0;
newIvl = LEARNING_STEPS.AGAIN;
newIsGraduated = false;
// Reduce factor but not below minimum
newFactor = Math.max(
FACTOR_CHANGES.MIN,
newFactor * FACTOR_CHANGES.AGAIN
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
if (action === 'again') {
newLapses++;
newReps = 0;
newIvl = LEARNING_STEPS.AGAIN;
newIsGraduated = false;
// Reduce factor but not below minimum
newFactor = Math.max(
FACTOR_CHANGES.MIN,
newFactor * FACTOR_CHANGES.AGAIN
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
if (action === 'easy') {
newReps++;
newIsGraduated = true;
newIvl = EASY_INTERVAL;
// Increase factor but not above maximum
newFactor = Math.min(
FACTOR_CHANGES.MAX,
newFactor * FACTOR_CHANGES.EASY
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };;
newReps++;
newIsGraduated = true;
newIvl = EASY_INTERVAL;
// Increase factor but not above maximum
newFactor = Math.min(
FACTOR_CHANGES.MAX,
newFactor * FACTOR_CHANGES.EASY
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
// Handle 'good' action
newReps++;
if (!newIsGraduated) {
// Card is in learning phase
if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD;
} else {
// Graduate the card
newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION;
}
// Card is in learning phase
if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD;
} else {
// Graduate the card
newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION;
}
} else {
// Card is in review phase, apply space repetition
newIvl = Math.round(newIvl * newFactor);
// Card is in review phase, apply space repetition
newIvl = Math.round(newIvl * newFactor);
}
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };;
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
/**
* Berechnet das nächste Intervall basierend auf der Aktion und gibt es als String zurück.
* @param box Die aktuelle Box
* @param action Die Aktion ('again', 'good', 'easy')
* @returns Das nächste Intervall als String (z.B. "10 min", "2 d")
* Calculates the next interval based on the action and returns it as a string.
* @param box The current box
* @param action The action ('again', 'good', 'easy')
* @returns The next interval as a string (e.g., "10 min", "2 d")
*/
getNextInterval(box: Box | null, action: 'again' | 'good' | 'easy'): string {
if (!box)
@ -340,18 +339,18 @@ export class TrainingComponent implements OnInit {
}
/**
* Formatiert das Intervall als String, entweder in Minuten oder Tagen.
* @param ivl Das Intervall in Tagen
* @returns Das formatierte Intervall als String
* Formats the interval as a string, either in minutes or days.
* @param ivl The interval in days
* @returns The formatted interval as a string
*/
formatInterval(minutes: number): string {
if (minutes < 60) return `${minutes}min`;
if (minutes < 1440) return `${Math.round(minutes/60)}h`;
return `${Math.round(minutes/1440)}d`;
if (minutes < 1440) return `${Math.round(minutes / 60)}h`;
return `${Math.round(minutes / 1440)}d`;
}
/**
* Deckt die aktuelle Box wieder auf (verdeckt sie erneut).
* Covers the current box again (hides it).
*/
coverCurrentBox(): void {
this.boxRevealed[this.currentBoxIndex] = false;
@ -359,24 +358,24 @@ export class TrainingComponent implements OnInit {
}
/**
* Geht zur nächsten Box. Wenn alle Boxen in der aktuellen Runde bearbeitet wurden,
* wird eine neue Runde gestartet.
* Moves to the next box. If all boxes in the current round have been processed,
* a new round is started.
*/
nextBox(): void {
this.isShowingBox = false;
if (this.currentBoxIndex >= this.boxesToReview.length - 1) {
// Runde abgeschlossen, starte eine neue Runde
// Round completed, start a new round
this.initializeBoxesToReview();
} else {
// Gehe zur nächsten Box
// Move to the next box
this.currentBoxIndex++;
this.drawCanvas();
}
}
/**
* Wechselt zum nächsten Bild im Deck.
* Moves to the next image in the deck.
*/
nextImage(): void {
this.currentImageIndex++;
@ -384,39 +383,39 @@ export class TrainingComponent implements OnInit {
}
/**
* Überspringt zum nächsten Bild im Deck.
* Skips to the next image in the deck.
*/
skipToNextImage(): void {
if (this.currentImageIndex < this.deck.images.length - 1) {
this.currentImageIndex++;
this.loadImage(this.currentImageIndex);
} else {
alert('Dies ist das letzte Bild im Deck.');
alert('This is the last image in the deck.');
}
}
/**
* Beendet das Training und gibt eine Abschlussmeldung aus.
* Ends the training and displays a completion message.
*/
endTraining(): void {
this.isTrainingFinished = true;
alert(`Training beendet!`);
alert(`Training completed!`);
this.close.emit();
}
/**
* Fragt den Benutzer, ob das Training beendet werden soll, und schließt es gegebenenfalls.
* Asks the user if they want to end the training and closes it if confirmed.
*/
closeTraining(): void {
if (confirm('Möchtest du das Training wirklich beenden?')) {
if (confirm('Do you really want to end the training?')) {
this.close.emit();
}
}
/**
* Gibt den Fortschritt des Trainings an, z.B. "Bild 2 von 5".
* Returns the progress of the training, e.g., "Image 2 of 5".
*/
get progress(): string {
return `Bild ${this.currentImageIndex + 1} von ${this.deck.images.length}`;
return `Image ${this.currentImageIndex + 1} of ${this.deck.images.length}`;
}
}
}

View File

@ -1,4 +1,3 @@
<!-- src/app/upload-image-modal.component.html -->
<div #uploadImageModal id="uploadImageModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
<div class="relative h-full contents">
<div class="relative bg-white rounded-lg shadow">
@ -6,29 +5,39 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Schließen</span>
<span class="sr-only">Close</span>
</button>
<div class="p-6 relative">
<h3 class="mb-4 text-xl font-medium text-gray-900">Bild zu Deck hinzufügen</h3>
<h3 class="mb-4 text-xl font-medium text-gray-900">Add Image to Deck</h3>
<!-- Formular zum Hochladen -->
<!-- Upload form -->
<div class="mb-4">
<label for="imageFile" class="block text-sm font-medium text-gray-700">Bild hochladen</label>
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" />
<!-- <label for="imageFile" class="block text-sm font-medium text-gray-700">Upload Image</label> -->
<!-- <input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" /> -->
<div class="relative">
<!-- Benutzerdefinierte Schaltfläche und Text -->
<label for="imageFile" class="block w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 cursor-pointer text-center">
Choose File
</label>
<!-- Das eigentliche Datei-Input-Feld -->
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="hidden" />
<!-- Anzeige des ausgewählten Dateinamens -->
<!-- <span id="fileName" class="block mt-2 text-sm text-gray-700 text-center">No file chosen</span> -->
</div>
</div>
<!-- Statusanzeige -->
<!-- Status display -->
<div *ngIf="processingStatus" class="mt-4">
<p class="text-sm text-gray-700">{{ processingStatus }}</p>
</div>
<!-- Ladeanzeige als Overlay -->
<!-- Loading overlay -->
<div *ngIf="loading" class="absolute inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center z-10">
<div class="bg-white p-4 rounded shadow">
<p class="text-sm text-gray-700">Verarbeitung läuft...</p>
<p class="text-sm text-gray-700">Processing in progress...</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -1,4 +1,3 @@
// src/app/upload-image-modal.component.ts
import { Component, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { Box, DeckImage, DeckService, OcrResult } from '../deck.service';
import { CommonModule } from '@angular/common';
@ -9,11 +8,20 @@ import { Modal } from 'flowbite';
selector: 'app-upload-image-modal',
templateUrl: './upload-image-modal.component.html',
standalone: true,
styles:`
label {
transition: background-color 0.3s ease;
}
label:hover {
background-color: #2563eb;
}
`,
imports: [CommonModule]
})
export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
@Input() deckName: string = '';
@Output() imageUploaded = new EventEmitter<{ imageSrc: string | ArrayBuffer | null | undefined, deckImage:DeckImage }>();
@Output() imageUploaded = new EventEmitter<{ imageSrc: string | ArrayBuffer | null | undefined, deckImage: DeckImage }>();
@ViewChild('uploadImageModal') modalElement!: ElementRef;
@ViewChild('imageFile') imageFileElement!: ElementRef;
@ -30,7 +38,7 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
}
ngOnDestroy(): void {
// Modal wird automatisch von Flowbite verwaltet
// Modal is automatically managed by Flowbite
}
open(): void {
@ -51,63 +59,68 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
onFileChange(event: any): void {
const file: File = event.target.files[0];
if (!file) return;
const fileNameElement = document.getElementById('fileName');
if (fileNameElement) {
fileNameElement.textContent = file.name;
}
this.imageFile = file;
this.processingStatus = 'Verarbeitung läuft...';
this.processingStatus = 'Processing in progress...';
this.loading = true;
const reader = new FileReader();
reader.onload = async (e) => {
const imageSrc = e.target?.result;
// Bild als Base64-String ohne Präfix (data:image/...)
// Image as Base64 string without prefix (data:image/...)
const imageBase64 = (imageSrc as string).split(',')[1];
try {
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
if (!response || !response.results) {
this.processingStatus = 'Ungültige Antwort vom OCR-Service';
this.processingStatus = 'Invalid response from OCR service';
this.loading = false;
return;
}
this.processingStatus = 'Verarbeitung abgeschlossen';
this.processingStatus = 'Processing complete';
this.loading = false;
// Emit Event mit Bilddaten und OCR-Ergebnissen
const bildname=this.imageFile?.name??'';
const bildid=response.results.length>0?response.results[0].name:null
const boxes:Box[] = [];
// Emit event with image data and OCR results
const imageName = this.imageFile?.name ?? '';
const imageId = response.results.length > 0 ? response.results[0].name : null;
const boxes: Box[] = [];
response.results.forEach((result: OcrResult) => {
const box = result.box;
const xs = box.map((point: number[]) => point[0]);
const ys = box.map((point: number[]) => point[1]);
const xMin = Math.min(...xs);
const xMax = Math.max(...xs);
const yMin = Math.min(...ys);
const yMax = Math.max(...ys);
boxes.push({x1:xMin,x2:xMax,y1:yMin,y2:yMax})
boxes.push({ x1: xMin, x2: xMax, y1: yMin, y2: yMax });
});
const deckImage:DeckImage={name:bildname,id:bildid,boxes}
const deckImage: DeckImage = { name: imageName, id: imageId, boxes };
this.imageUploaded.emit({ imageSrc, deckImage });
this.resetFileInput();
// Schließe das Upload-Modal
// Close the upload modal
this.closeModal();
} catch (error) {
console.error('Fehler beim OCR-Service:', error);
this.processingStatus = 'Fehler beim OCR-Service';
console.error('Error with OCR service:', error);
this.processingStatus = 'Error with OCR service';
this.loading = false;
}
};
reader.readAsDataURL(file);
}
/**
* Setzt das Datei-Input-Feld zurück, sodass dieselbe Datei erneut ausgewählt werden kann.
* Resets the file input field so the same file can be selected again.
*/
resetFileInput(): void {
if (this.imageFileElement && this.imageFileElement.nativeElement) {
this.imageFileElement.nativeElement.value = '';
}
}
}
}