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', selector: 'app-root',
template: ` template: `
<div class="container mx-auto p-4"> <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> <app-deck-list></app-deck-list>
</div> </div>
`, `,
standalone: true, standalone: true,
imports: [ CommonModule, DeckListComponent] imports: [CommonModule, DeckListComponent]
}) })
export class AppComponent { export class AppComponent {
title = 'vokabeltraining'; title = 'vocabulary-training';
ngOnInit(): void { ngOnInit(): void {
initFlowbite(); 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 #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 w-full h-full max-w-md md:h-auto">
<div class="relative bg-white rounded-lg shadow"> <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"> <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> <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> </svg>
<span class="sr-only">Schließen</span> <span class="sr-only">Close</span>
</button> </button>
<div class="p-6"> <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)"> <form (submit)="createDeck($event)">
<div class="mb-4"> <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" /> <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> </div>
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"> <button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Erstellen Create
</button> </button>
</form> </form>
</div> </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 { Component, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { DeckService } from '../deck.service'; import { DeckService } from '../deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -30,7 +29,7 @@ export class CreateDeckModalComponent implements AfterViewInit {
createDeck(event: Event): void { createDeck(event: Event): void {
event.preventDefault(); event.preventDefault();
if (this.deckName.trim() === '') { if (this.deckName.trim() === '') {
alert('Bitte einen Deck-Namen eingeben.'); alert('Please enter a deck name.');
return; return;
} }
@ -41,8 +40,8 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.modal.hide(); this.modal.hide();
}, },
error: (err) => { error: (err) => {
console.error('Fehler beim Erstellen des Decks', err); console.error('Error creating deck', err);
alert('Fehler beim Erstellen des Decks.'); alert('Error creating deck.');
} }
}); });
} }
@ -50,5 +49,4 @@ export class CreateDeckModalComponent implements AfterViewInit {
closeModal(): void { closeModal(): void {
this.modal.hide(); this.modal.hide();
} }
} }

View File

@ -1,22 +1,21 @@
<!-- src/app/deck-list.component.html -->
<div> <div>
<!-- Button zum Erstellen eines neuen Decks --> <!-- Button to create a new deck -->
<div class="flex justify-end mb-4"> <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"> <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> </button>
</div> </div>
<!-- Decks anzeigen --> <!-- Display decks -->
<div class="flex flex-wrap"> <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"> <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 justify-between items-center mb-4">
<div class="flex items-center space-x-2"> <div class="flex items-center space-x-2">
<h2 class="text-xl font-semibold">{{ deck.name }}</h2> <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> </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"> <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" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg> </svg>
@ -26,54 +25,54 @@
</button> </button>
</div> </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"> <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"> <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"> <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="flex items-center space-x-2">
<div class="relative group"> <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"> <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"> <img src="/api/debug_image/{{image.id}}/thumbnail.jpg" alt="{{ image.name }}" class="w-full h-auto object-cover">
</div> </div>
<!-- Bildname mit Tooltip --> <!-- Image name with tooltip -->
<span class="font-medium cursor-pointer"> <span class="font-medium cursor-pointer">
{{ image.name }} {{ image.name }}
</span> </span>
</div> </div>
<span class="text-gray-600">({{ image.boxes.length }} Boxen)</span> <span class="text-gray-600">({{ image.boxes.length }} boxes)</span>
</div> </div>
<div class="flex space-x-2"> <div class="flex space-x-2">
<!-- Edit Icon --> <!-- 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"> <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" /> <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> </svg>
</button> </button>
<!-- Delete Icon --> <!-- 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"> <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" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg> </svg>
</button> </button>
<!-- Move Icon --> <!-- 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"> <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" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg> </svg>
</button> </button>
</div> </div>
</li> </li>
</ul> </ul>
<!-- Action-Buttons --> <!-- Action buttons -->
<div class="flex space-x-2"> <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"> <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>
<button (click)="openUploadImageModal(deck.name)" class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600"> <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> </button>
</div> </div>
</ng-container> </ng-container>
@ -84,18 +83,17 @@
<app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal> <app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal>
<!-- UploadImageModalComponent --> <!-- 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> <app-edit-image-modal *ngIf="imageData" [deckName]="currentUploadDeckName" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
<!-- TrainingComponent --> <!-- TrainingComponent -->
<app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training> <app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training>
<!-- MoveImageModalComponent --> <!-- MoveImageModalComponent -->
<app-move-image-modal <app-move-image-modal
*ngIf="imageToMove" *ngIf="imageToMove"
[image]="imageToMove.image" [image]="imageToMove.image"
[sourceDeck]="imageToMove.sourceDeck" [sourceDeck]="imageToMove.sourceDeck"
[decks]="decks" [decks]="decks"
(moveCompleted)="onImageMoved()" (moveCompleted)="onImageMoved()"
(closed)="imageToMove = null"> (closed)="imageToMove = null">
</app-move-image-modal> </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 { Component, OnInit, ViewChild } from '@angular/core';
import { DeckService, Deck, DeckImage } from './deck.service'; import { DeckService, Deck, DeckImage } from './deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -19,7 +18,7 @@ import { MoveImageModalComponent } from './move-image-modal/move-image-modal.com
UploadImageModalComponent, UploadImageModalComponent,
TrainingComponent, TrainingComponent,
EditImageModalComponent, EditImageModalComponent,
MoveImageModalComponent, // Hinzufügen der neuen Komponente MoveImageModalComponent, // Adding the new component
UploadImageModalComponent UploadImageModalComponent
] ]
}) })
@ -36,10 +35,10 @@ export class DeckListComponent implements OnInit {
currentUploadDeckName: string = ''; currentUploadDeckName: string = '';
// Set zur Verfolgung erweiterter Decks // Set to track expanded decks
expandedDecks: Set<string> = new Set<string>(); expandedDecks: Set<string> = new Set<string>();
// State für das Verschieben von Bildern // State for moving images
imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null; imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null;
constructor(private deckService: DeckService) { } constructor(private deckService: DeckService) { }
@ -52,56 +51,56 @@ export class DeckListComponent implements OnInit {
loadDecks(): void { loadDecks(): void {
this.deckService.getDecks().subscribe({ this.deckService.getDecks().subscribe({
next: (data) => this.decks = data, 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 { 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; return;
} }
this.deckService.deleteDeck(deckName).subscribe({ this.deckService.deleteDeck(deckName).subscribe({
next: () => this.loadDecks(), 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 { 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; return;
} }
const imageId = image.id; const imageId = image.id;
this.deckService.deleteImage(imageId).subscribe({ this.deckService.deleteImage(imageId).subscribe({
next: () => this.loadDecks(), 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 { editImage(deck: Deck, image: DeckImage): void {
let imageSrc = null let imageSrc = null;
this.currentUploadDeckName = deck.name; this.currentUploadDeckName = deck.name;
fetch(`/api/debug_image/${image.id}/original_compressed.jpg`) fetch(`/api/debug_image/${image.id}/original_compressed.jpg`)
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error('Netzwerkantwort war nicht ok'); throw new Error('Network response was not ok');
} }
return response.blob(); return response.blob();
}) })
.then(blob => { .then(blob => {
const reader = new FileReader(); const reader = new FileReader();
reader.onloadend = () => { reader.onloadend = () => {
imageSrc = reader.result; // Base64-String imageSrc = reader.result; // Base64 string
this.imageData = { imageSrc, deckImage: image } this.imageData = { imageSrc, deckImage: image };
}; };
reader.readAsDataURL(blob); reader.readAsDataURL(blob);
}) })
.catch(error => { .catch(error => {
console.error('Fehler beim Laden des Bildes:', error); console.error('Error loading image:', error);
}); });
} }
openTraining(deck: Deck): void { openTraining(deck: Deck): void {
this.selectedDeck = deck; this.selectedDeck = deck;
} }
@ -121,7 +120,7 @@ export class DeckListComponent implements OnInit {
this.uploadImageModal.open(); this.uploadImageModal.open();
} }
// Methode zum Umschalten der Deck-Erweiterung // Method to toggle deck expansion
toggleDeckExpansion(deckName: string): void { toggleDeckExpansion(deckName: string): void {
if (this.expandedDecks.has(deckName)) { if (this.expandedDecks.has(deckName)) {
this.expandedDecks.delete(deckName); this.expandedDecks.delete(deckName);
@ -131,12 +130,12 @@ export class DeckListComponent implements OnInit {
this.saveExpandedDecks(); this.saveExpandedDecks();
} }
// Methode zur Überprüfung, ob ein Deck erweitert ist // Method to check if a deck is expanded
isDeckExpanded(deckName: string): boolean { isDeckExpanded(deckName: string): boolean {
return this.expandedDecks.has(deckName); return this.expandedDecks.has(deckName);
} }
// Laden der erweiterten Decks aus dem sessionStorage // Load expanded decks from sessionStorage
loadExpandedDecks(): void { loadExpandedDecks(): void {
const stored = sessionStorage.getItem('expandedDecks'); const stored = sessionStorage.getItem('expandedDecks');
if (stored) { if (stored) {
@ -144,48 +143,48 @@ export class DeckListComponent implements OnInit {
const parsed: string[] = JSON.parse(stored); const parsed: string[] = JSON.parse(stored);
this.expandedDecks = new Set<string>(parsed); this.expandedDecks = new Set<string>(parsed);
} catch (e) { } catch (e) {
console.error('Fehler beim Parsen der erweiterten Decks aus sessionStorage', e); console.error('Error parsing expanded decks from sessionStorage', e);
} }
} else { } 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>(); this.expandedDecks = new Set<string>();
} }
} }
// Speichern der erweiterten Decks in das sessionStorage // Save expanded decks to sessionStorage
saveExpandedDecks(): void { saveExpandedDecks(): void {
const expandedArray = Array.from(this.expandedDecks); const expandedArray = Array.from(this.expandedDecks);
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray)); 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 { openUploadModal(): void {
this.uploadImageModal.open(); this.uploadImageModal.open();
} }
// Handler für das imageUploaded Event // Handler for the imageUploaded event
onImageUploaded(imageData: any): void { onImageUploaded(imageData: any): void {
this.imageData = imageData; this.imageData = imageData;
} }
onClosed(){ onClosed() {
this.imageData = null; this.imageData = null;
} }
async onImageSaved() { 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.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 { openMoveImageModal(deck: Deck, image: DeckImage): void {
this.imageToMove = { image, sourceDeck: deck }; this.imageToMove = { image, sourceDeck: deck };
} }
// Handler für das moveCompleted Event // Handler for the moveCompleted event
onImageMoved(): void { onImageMoved(): void {
this.imageToMove = null; this.imageToMove = null;
this.loadDecks(); this.loadDecks();
} }
} }

View File

@ -1,4 +1,3 @@
// src/app/deck.service.ts
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { map, Observable, switchMap } from 'rxjs'; import { map, Observable, switchMap } from 'rxjs';
@ -11,21 +10,21 @@ export interface Deck {
export interface DeckImage { export interface DeckImage {
boxes: Box[]; boxes: Box[];
name: string; name: string;
id:string; id: string;
} }
export interface Box { export interface Box {
id?:number; id?: number;
x1:number; x1: number;
x2:number; x2: number;
y1:number; y1: number;
y2:number; y2: number;
due?: number; due?: number;
ivl?: number; ivl?: number;
factor?: number; factor?: number;
reps?: number; reps?: number;
lapses?: number; lapses?: number;
isGraduated?:boolean; isGraduated?: boolean;
} }
export interface BackendBox { export interface BackendBox {
@ -39,13 +38,13 @@ export interface BackendBox {
y2: number; y2: number;
} }
// Definiert ein einzelnes Punktpaar [x, y] // Defines a single point pair [x, y]
type OcrPoint = [number, number]; 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]; type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint];
// Interface für jedes JSON-Objekt // Interface for each JSON object
export interface OcrResult { export interface OcrResult {
box: OcrBox; box: OcrBox;
confidence: number; confidence: number;
@ -69,6 +68,7 @@ export class DeckService {
}))) })))
); );
} }
private groupImagesByName(images: any[]): DeckImage[] { private groupImagesByName(images: any[]): DeckImage[] {
const imageMap: { [key: string]: DeckImage } = {}; const imageMap: { [key: string]: DeckImage } = {};
@ -76,7 +76,7 @@ export class DeckService {
if (!imageMap[image.id]) { if (!imageMap[image.id]) {
imageMap[image.id] = { imageMap[image.id] = {
name: image.name, name: image.name,
id:image.id, id: image.id,
boxes: [] boxes: []
}; };
} }
@ -87,17 +87,18 @@ export class DeckService {
y1: image.y1, y1: image.y1,
y2: image.y2, y2: image.y2,
due: image.due, due: image.due,
ivl:image.ivl, ivl: image.ivl,
factor:image.factor, factor: image.factor,
reps:image.reps, reps: image.reps,
lapses:image.lapses, lapses: image.lapses,
isGraduated:image.isGraduated?true:false isGraduated: image.isGraduated ? true : false
}); });
}); });
return Object.values(imageMap); return Object.values(imageMap);
} }
getDeck(deckname:string): Observable<Deck> {
getDeck(deckname: string): Observable<Deck> {
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`); return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
} }
@ -109,16 +110,16 @@ export class DeckService {
return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`); 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); 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> { deleteImage(imageName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/image/${imageName}`); 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> { moveImage(imageId: string, targetDeckId: number): Observable<any> {
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId }); return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId });
} }
@ -126,4 +127,4 @@ export class DeckService {
updateBox(box: Box): Observable<any> { updateBox(box: Box): Observable<any> {
return this.http.put(`${this.apiUrl}/boxes/${box.id}`, box); 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 #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 h-full contents">
<div class="relative bg-white rounded-lg shadow"> <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"> <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> <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> </svg>
<span class="sr-only">Schließen</span> <span class="sr-only">Close</span>
</button> </button>
<div class="p-6 relative"> <div class="p-6 relative">
<!-- Überschrift mit Boxanzahl --> <!-- Header with box count -->
<h3 class="mb-4 text-xl font-medium text-gray-900"> <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> </h3>
<!-- Canvas --> <!-- Canvas -->
@ -19,16 +18,16 @@
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas> <canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
</div> </div>
<!-- Buttons unter dem Canvas --> <!-- Buttons below the canvas -->
<div class="mt-4 flex justify-between"> <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"> <button (click)="save()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Save Save
</button> </button>
<button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"> <button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Neue Box New Box
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -12,11 +12,11 @@ import { DeckImage, DeckService, OcrResult } from '../deck.service';
imports: [CommonModule] imports: [CommonModule]
}) })
export class EditImageModalComponent implements AfterViewInit, OnDestroy { export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// Konstante für die Boxfarbe // Constant for box color
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Rot mit Transparenz private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Red with transparency
@Input() deckName: string = ''; @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() imageSaved = new EventEmitter<void>();
@Output() closed = new EventEmitter<void>(); @Output() closed = new EventEmitter<void>();
@ViewChild('editImageModal') modalElement!: ElementRef; @ViewChild('editImageModal') modalElement!: ElementRef;
@ -35,11 +35,11 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
constructor(private deckService: DeckService) { } constructor(private deckService: DeckService) { }
async ngAfterViewInit() { async ngAfterViewInit() {
this.modal = new Modal(this.modalElement.nativeElement,{ this.modal = new Modal(this.modalElement.nativeElement, {
onHide: () => { onHide: () => {
this.closed.emit(); this.closed.emit();
}}, }
); });
this.maxCanvasWidth = window.innerWidth * 0.6; this.maxCanvasWidth = window.innerWidth * 0.6;
this.maxCanvasHeight = window.innerHeight * 0.6; this.maxCanvasHeight = window.innerHeight * 0.6;
@ -89,13 +89,13 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
async processImage(): Promise<void> { async processImage(): Promise<void> {
try { try {
if (!this.imageData){ if (!this.imageData) {
return; return;
} }
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement); this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
// Hintergrundbild setzen // Set background image
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string); const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
const originalWidth = backgroundImage.width!; const originalWidth = backgroundImage.width!;
@ -120,7 +120,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.boxes = []; this.boxes = [];
// Boxen hinzufügen // Add boxes
this.imageData.deckImage?.boxes.forEach(box => { this.imageData.deckImage?.boxes.forEach(box => {
const rect = new fabric.Rect({ const rect = new fabric.Rect({
@ -128,7 +128,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: box.y1 * scaleFactor, top: box.y1 * scaleFactor,
width: (box.x2 - box.x1) * scaleFactor, width: (box.x2 - box.x1) * scaleFactor,
height: (box.y2 - box.y1) * scaleFactor, height: (box.y2 - box.y1) * scaleFactor,
fill: this.BOX_COLOR, // Verwendung der Konstante fill: this.BOX_COLOR, // Use the constant
selectable: true, selectable: true,
hasControls: true, hasControls: true,
hasBorders: true, hasBorders: true,
@ -159,7 +159,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// this.detectedText = ocrResults.map(result => result.text).join('\n'); // this.detectedText = ocrResults.map(result => result.text).join('\n');
} catch (error) { } 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, top: (canvasHeight - boxHeight) / 2,
width: boxWidth, width: boxWidth,
height: boxHeight, height: boxHeight,
fill: this.BOX_COLOR, // Verwendung der Konstante fill: this.BOX_COLOR, // Use the constant
selectable: true, selectable: true,
hasControls: true, hasControls: true,
hasBorders: true, hasBorders: true,
@ -252,8 +252,8 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
} }
save(): void { save(): void {
// Hier implementierst du die Logik zum Speichern der Bilddaten // Implement the logic to save the image data here
// Zum Beispiel über einen Service oder direkt hier // For example, via a service or directly here
const data = { const data = {
deckname: this.deckName, deckname: this.deckName,
bildname: this.imageData.deckImage?.name, // this.imageFile?.name, bildname: this.imageData.deckImage?.name, // this.imageFile?.name,
@ -266,10 +266,10 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.closeModal(); this.closeModal();
}, },
error: (err) => { error: (err) => {
console.error('Fehler beim Speichern des Bildes:', err); console.error('Error saving image:', err);
alert('Fehler beim Speichern des Bildes.'); alert('Error saving image.');
this.closeModal(); 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="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"> <div class="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Bild verschieben</h2> <h2 class="text-xl font-semibold mb-4">Move Image</h2>
<p class="mb-4">Wähle das Zieldeck für das Bild <strong>{{ image.name }}</strong> aus.</p> <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"> <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"> <option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
{{ deck.name }} {{ deck.name }}
</option> </option>
</select> </select>
<div class="flex justify-end space-x-2"> <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"> <button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
Abbrechen Cancel
</button> </button>
<button <button
(click)="moveImage()" (click)="moveImage()"
[disabled]="!selectedDeckId" [disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600"> class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Verschieben Move
</button> </button>
</div>
</div> </div>
</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 { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { DeckImage, Deck, DeckService } from '../deck.service'; import { DeckImage, Deck, DeckService } from '../deck.service';
@ -33,8 +31,8 @@ export class MoveImageModalComponent {
this.close(); this.close();
}, },
error: (err) => { error: (err) => {
console.error('Fehler beim Verschieben des Bildes:', err); console.error('Error moving image:', err);
alert('Fehler beim Verschieben des Bildes.'); alert('Error moving image.');
} }
}); });
} }
@ -42,4 +40,4 @@ export class MoveImageModalComponent {
close(): void { close(): void {
this.closed.emit(); this.closed.emit();
} }
} }

View File

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

View File

@ -1,4 +1,3 @@
// training.component.ts
import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core'; import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Deck, DeckImage, DeckService, Box } from '../deck.service'; import { Deck, DeckImage, DeckService, Box } from '../deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -27,7 +26,7 @@ export class TrainingComponent implements OnInit {
@Input() deck!: Deck; @Input() deck!: Deck;
@Output() close = new EventEmitter<void>(); @Output() close = new EventEmitter<void>();
@ViewChild('canvas',{static : false}) canvasRef!: ElementRef<HTMLCanvasElement>; @ViewChild('canvas', { static: false }) canvasRef!: ElementRef<HTMLCanvasElement>;
currentImageIndex: number = 0; currentImageIndex: number = 0;
currentImageData: DeckImage | null = null; currentImageData: DeckImage | null = null;
@ -41,22 +40,22 @@ export class TrainingComponent implements OnInit {
constructor(private deckService: DeckService) { } constructor(private deckService: DeckService) { }
ngOnInit(): void { ngOnInit(): void {
// Initialisierung wurde in ngAfterViewInit durchgeführt // Initialization was done in ngAfterViewInit
} }
ngAfterViewInit(){ ngAfterViewInit() {
// Initialisiere das erste Bild und die dazugehörigen Boxen // Initialize the first image and its boxes
if (this.deck && this.deck.images.length > 0) { if (this.deck && this.deck.images.length > 0) {
this.loadImage(this.currentImageIndex); this.loadImage(this.currentImageIndex);
} else { } else {
alert('Kein Deck oder keine Bilder vorhanden.'); alert('No deck or images available.');
this.close.emit(); this.close.emit();
} }
} }
/** /**
* Lädt das Bild basierend auf dem gegebenen Index und initialisiert die zu überprüfenden Boxen. * Loads the image based on the given index and initializes the boxes to review.
* @param imageIndex Index des zu ladenden Bildes im Deck * @param imageIndex Index of the image to load in the deck
*/ */
loadImage(imageIndex: number): void { loadImage(imageIndex: number): void {
if (imageIndex >= this.deck.images.length) { if (imageIndex >= this.deck.images.length) {
@ -65,13 +64,13 @@ export class TrainingComponent implements OnInit {
} }
this.currentImageData = this.deck.images[imageIndex]; this.currentImageData = this.deck.images[imageIndex];
// Initialisiere die Boxen für die aktuelle Runde // Initialize the boxes for the current round
this.initializeBoxesToReview(); this.initializeBoxesToReview();
} }
/** /**
* Ermittelt alle fälligen Boxen für die aktuelle Runde, mischt sie und setzt den aktuellen Box-Index zurück. * Determines all due boxes for the current round, shuffles them, and resets the current box index.
* Wenn keine Boxen mehr zu überprüfen sind, wird zum nächsten Bild gewechselt. * If no boxes are left to review, it moves to the next image.
*/ */
initializeBoxesToReview(): void { initializeBoxesToReview(): void {
if (!this.currentImageData) { if (!this.currentImageData) {
@ -79,42 +78,42 @@ export class TrainingComponent implements OnInit {
return; return;
} }
// Filtere alle Boxen, die fällig sind (due <= heute) // Filter all boxes that are due (due <= today)
const today = this.getTodayInDays(); const today = this.getTodayInDays();
this.boxesToReview = this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today); this.boxesToReview = this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today);
if (this.boxesToReview.length === 0) { 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(); this.nextImage();
return; return;
} }
// Mische die Boxen zufällig // Shuffle the boxes randomly
this.boxesToReview = this.shuffleArray(this.boxesToReview); 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); 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.currentBoxIndex = 0;
this.isShowingBox = false; this.isShowingBox = false;
// Zeichne das Canvas neu // Redraw the canvas
this.drawCanvas(); 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 { 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(); const today = new Date();
return Math.floor((today.getTime() - epoch.getTime()) / (1000 * 60 * 60 * 24)); return Math.floor((today.getTime() - epoch.getTime()) / (1000 * 60 * 60 * 24));
} }
/** /**
* Zeichnet das aktuelle Bild und die Boxen auf das Canvas. * Draws the current image and boxes on the canvas.
* Boxen werden rot dargestellt, wenn sie verdeckt sind, und grün, wenn sie enthüllt sind. * Boxes are displayed in red if hidden and green if revealed.
*/ */
drawCanvas(): void { drawCanvas(): void {
const canvas = this.canvasRef.nativeElement; const canvas = this.canvasRef.nativeElement;
@ -124,27 +123,27 @@ export class TrainingComponent implements OnInit {
const img = new Image(); const img = new Image();
img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`; img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`;
img.onload = () => { 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.width = img.width;
canvas.height = img.height; canvas.height = img.height;
// Zeichne das Bild // Draw the image
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 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) => { this.boxesToReview.forEach((box, index) => {
ctx.beginPath(); ctx.beginPath();
ctx.rect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1); 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)) { if (this.currentBoxIndex === index && this.isShowingBox || (box.due && box.due - this.getTodayInDays() > 0)) {
// Box ist aktuell enthüllt, keine Überlagerung // Box is currently revealed, no overlay
return; return;
} else if (this.currentBoxIndex === index && !this.isShowingBox) { } else if (this.currentBoxIndex === index && !this.isShowingBox) {
// Box ist enthüllt // Box is revealed
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Undurchsichtige grüne Überlagerung ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Opaque green overlay
} else { } else {
// Box ist verdeckt // Box is hidden
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Undurchsichtige rote Überlagerung ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Opaque red overlay
} }
ctx.fill(); ctx.fill();
ctx.lineWidth = 2; ctx.lineWidth = 2;
@ -154,27 +153,27 @@ export class TrainingComponent implements OnInit {
}; };
img.onerror = () => { img.onerror = () => {
console.error('Fehler beim Laden des Bildes für Canvas.'); console.error('Error loading image for canvas.');
alert('Fehler beim Laden des Bildes für Canvas.'); alert('Error loading image for canvas.');
this.close.emit(); this.close.emit();
}; };
} }
/** /**
* Mischt ein Array zufällig. * Shuffles an array randomly.
* @param array Das zu mischende Array * @param array The array to shuffle
* @returns Das gemischte Array * @returns The shuffled array
*/ */
shuffleArray<T>(array: T[]): T[] { shuffleArray<T>(array: T[]): T[] {
let currentIndex = array.length, randomIndex; let currentIndex = array.length, randomIndex;
// Solange noch Elemente zum Mischen vorhanden sind // While there are elements to shuffle
while (currentIndex !== 0) { while (currentIndex !== 0) {
// Wähle ein verbleibendes Element // Pick a remaining element
randomIndex = Math.floor(Math.random() * currentIndex); randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--; currentIndex--;
// Tausche es mit dem aktuellen Element // Swap it with the current element
[array[currentIndex], array[randomIndex]] = [ [array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]]; 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 { get currentBox(): Box | null {
if (this.currentBoxIndex < this.boxesToReview.length) { 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 { showText(): void {
if (this.currentBoxIndex >= this.boxesToReview.length) return; 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> { async markAgain(): Promise<void> {
await this.updateCard('again'); 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> { async markGood(): Promise<void> {
await this.updateCard('good'); 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> { async markEasy(): Promise<void> {
await this.updateCard('easy'); 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. * Updates the SRS data of the current box based on the given action.
* @param action Die durchgeführte Aktion ('again', 'good', 'easy') * @param action The action performed ('again', 'good', 'easy')
*/ */
async updateCard(action: 'again' | 'good' | 'easy'): Promise<void> { async updateCard(action: 'again' | 'good' | 'easy'): Promise<void> {
if (this.currentBoxIndex >= this.boxesToReview.length) return; if (this.currentBoxIndex >= this.boxesToReview.length) return;
@ -239,96 +238,96 @@ export class TrainingComponent implements OnInit {
const box = this.boxesToReview[this.currentBoxIndex]; const box = this.boxesToReview[this.currentBoxIndex];
const today = this.getTodayInDays(); 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); const { newIvl, newFactor, newReps, newLapses, newIsGraduated } = this.calculateNewInterval(box, action);
// Aktualisiere das Fälligkeitsdatum // Update the due date
const nextDue = today + Math.floor(newIvl/1440); const nextDue = today + Math.floor(newIvl / 1440);
// Aktualisiere das Box-Objekt // Update the box object
box.ivl = newIvl; box.ivl = newIvl;
box.factor = newFactor; box.factor = newFactor;
box.reps = newReps; box.reps = newReps;
box.lapses = newLapses; box.lapses = newLapses;
box.due = nextDue; box.due = nextDue;
box.isGraduated = newIsGraduated box.isGraduated = newIsGraduated;
// Sende das Update an das Backend // Send the update to the backend
try { try {
await lastValueFrom(this.deckService.updateBox(box)); await lastValueFrom(this.deckService.updateBox(box));
} catch (error) { } catch (error) {
console.error('Fehler beim Aktualisieren der Box:', error); console.error('Error updating box:', error);
alert('Fehler beim Aktualisieren der Box.'); alert('Error updating box.');
} }
} }
/** /**
* Berechnet das neue Intervall, den Faktor, die Wiederholungen und die Lapses basierend auf der Aktion. * Calculates the new interval, factor, repetitions, and lapses based on the action.
* @param box Die aktuelle Box * @param box The current box
* @param action Die Aktion ('again', 'good', 'easy') * @param action The action ('again', 'good', 'easy')
* @returns Ein Objekt mit den neuen Werten für ivl, factor, reps und lapses * @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 } { calculateNewInterval(box: Box, action: 'again' | 'good' | 'easy'): { newIvl: number, newFactor: number, newReps: number, newLapses: number, newIsGraduated: boolean } {
let newIvl = box.ivl || 0; let newIvl = box.ivl || 0;
let newFactor = box.factor || 2.5; let newFactor = box.factor || 2.5;
let newReps = box.reps || 0; let newReps = box.reps || 0;
let newLapses = box.lapses || 0; let newLapses = box.lapses || 0;
let newIsGraduated = box.isGraduated || false let newIsGraduated = box.isGraduated || false;
if (action === 'again') { if (action === 'again') {
newLapses++; newLapses++;
newReps = 0; newReps = 0;
newIvl = LEARNING_STEPS.AGAIN; newIvl = LEARNING_STEPS.AGAIN;
newIsGraduated = false; newIsGraduated = false;
// Reduce factor but not below minimum // Reduce factor but not below minimum
newFactor = Math.max( newFactor = Math.max(
FACTOR_CHANGES.MIN, FACTOR_CHANGES.MIN,
newFactor * FACTOR_CHANGES.AGAIN newFactor * FACTOR_CHANGES.AGAIN
); );
return { newIvl, newFactor, newReps, newLapses, newIsGraduated }; return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
} }
if (action === 'easy') { if (action === 'easy') {
newReps++; newReps++;
newIsGraduated = true; newIsGraduated = true;
newIvl = EASY_INTERVAL; newIvl = EASY_INTERVAL;
// Increase factor but not above maximum // Increase factor but not above maximum
newFactor = Math.min( newFactor = Math.min(
FACTOR_CHANGES.MAX, FACTOR_CHANGES.MAX,
newFactor * FACTOR_CHANGES.EASY newFactor * FACTOR_CHANGES.EASY
); );
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };; return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
} }
// Handle 'good' action // Handle 'good' action
newReps++; newReps++;
if (!newIsGraduated) { if (!newIsGraduated) {
// Card is in learning phase // Card is in learning phase
if (newReps === 1) { if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD; newIvl = LEARNING_STEPS.GOOD;
} else { } else {
// Graduate the card // Graduate the card
newIsGraduated = true; newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION; newIvl = LEARNING_STEPS.GRADUATION;
} }
} else { } else {
// Card is in review phase, apply space repetition // Card is in review phase, apply space repetition
newIvl = Math.round(newIvl * newFactor); 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. * Calculates the next interval based on the action and returns it as a string.
* @param box Die aktuelle Box * @param box The current box
* @param action Die Aktion ('again', 'good', 'easy') * @param action The action ('again', 'good', 'easy')
* @returns Das nächste Intervall als String (z.B. "10 min", "2 d") * @returns The next interval as a string (e.g., "10 min", "2 d")
*/ */
getNextInterval(box: Box | null, action: 'again' | 'good' | 'easy'): string { getNextInterval(box: Box | null, action: 'again' | 'good' | 'easy'): string {
if (!box) if (!box)
@ -340,18 +339,18 @@ export class TrainingComponent implements OnInit {
} }
/** /**
* Formatiert das Intervall als String, entweder in Minuten oder Tagen. * Formats the interval as a string, either in minutes or days.
* @param ivl Das Intervall in Tagen * @param ivl The interval in days
* @returns Das formatierte Intervall als String * @returns The formatted interval as a string
*/ */
formatInterval(minutes: number): string { formatInterval(minutes: number): string {
if (minutes < 60) return `${minutes}min`; if (minutes < 60) return `${minutes}min`;
if (minutes < 1440) return `${Math.round(minutes/60)}h`; if (minutes < 1440) return `${Math.round(minutes / 60)}h`;
return `${Math.round(minutes/1440)}d`; return `${Math.round(minutes / 1440)}d`;
} }
/** /**
* Deckt die aktuelle Box wieder auf (verdeckt sie erneut). * Covers the current box again (hides it).
*/ */
coverCurrentBox(): void { coverCurrentBox(): void {
this.boxRevealed[this.currentBoxIndex] = false; 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, * Moves to the next box. If all boxes in the current round have been processed,
* wird eine neue Runde gestartet. * a new round is started.
*/ */
nextBox(): void { nextBox(): void {
this.isShowingBox = false; this.isShowingBox = false;
if (this.currentBoxIndex >= this.boxesToReview.length - 1) { if (this.currentBoxIndex >= this.boxesToReview.length - 1) {
// Runde abgeschlossen, starte eine neue Runde // Round completed, start a new round
this.initializeBoxesToReview(); this.initializeBoxesToReview();
} else { } else {
// Gehe zur nächsten Box // Move to the next box
this.currentBoxIndex++; this.currentBoxIndex++;
this.drawCanvas(); this.drawCanvas();
} }
} }
/** /**
* Wechselt zum nächsten Bild im Deck. * Moves to the next image in the deck.
*/ */
nextImage(): void { nextImage(): void {
this.currentImageIndex++; 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 { skipToNextImage(): void {
if (this.currentImageIndex < this.deck.images.length - 1) { if (this.currentImageIndex < this.deck.images.length - 1) {
this.currentImageIndex++; this.currentImageIndex++;
this.loadImage(this.currentImageIndex); this.loadImage(this.currentImageIndex);
} else { } 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 { endTraining(): void {
this.isTrainingFinished = true; this.isTrainingFinished = true;
alert(`Training beendet!`); alert(`Training completed!`);
this.close.emit(); 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 { closeTraining(): void {
if (confirm('Möchtest du das Training wirklich beenden?')) { if (confirm('Do you really want to end the training?')) {
this.close.emit(); 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 { 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 #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 h-full contents">
<div class="relative bg-white rounded-lg shadow"> <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"> <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> <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> </svg>
<span class="sr-only">Schließen</span> <span class="sr-only">Close</span>
</button> </button>
<div class="p-6 relative"> <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"> <div class="mb-4">
<label for="imageFile" class="block text-sm font-medium text-gray-700">Bild hochladen</label> <!-- <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" /> <!-- <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> </div>
<!-- Statusanzeige --> <!-- Status display -->
<div *ngIf="processingStatus" class="mt-4"> <div *ngIf="processingStatus" class="mt-4">
<p class="text-sm text-gray-700">{{ processingStatus }}</p> <p class="text-sm text-gray-700">{{ processingStatus }}</p>
</div> </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 *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"> <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> </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 { Component, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { Box, DeckImage, DeckService, OcrResult } from '../deck.service'; import { Box, DeckImage, DeckService, OcrResult } from '../deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -9,11 +8,20 @@ import { Modal } from 'flowbite';
selector: 'app-upload-image-modal', selector: 'app-upload-image-modal',
templateUrl: './upload-image-modal.component.html', templateUrl: './upload-image-modal.component.html',
standalone: true, standalone: true,
styles:`
label {
transition: background-color 0.3s ease;
}
label:hover {
background-color: #2563eb;
}
`,
imports: [CommonModule] imports: [CommonModule]
}) })
export class UploadImageModalComponent implements AfterViewInit, OnDestroy { export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
@Input() deckName: string = ''; @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('uploadImageModal') modalElement!: ElementRef;
@ViewChild('imageFile') imageFileElement!: ElementRef; @ViewChild('imageFile') imageFileElement!: ElementRef;
@ -30,7 +38,7 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
// Modal wird automatisch von Flowbite verwaltet // Modal is automatically managed by Flowbite
} }
open(): void { open(): void {
@ -51,63 +59,68 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
onFileChange(event: any): void { onFileChange(event: any): void {
const file: File = event.target.files[0]; const file: File = event.target.files[0];
if (!file) return; if (!file) return;
const fileNameElement = document.getElementById('fileName');
if (fileNameElement) {
fileNameElement.textContent = file.name;
}
this.imageFile = file; this.imageFile = file;
this.processingStatus = 'Verarbeitung läuft...'; this.processingStatus = 'Processing in progress...';
this.loading = true; this.loading = true;
const reader = new FileReader(); const reader = new FileReader();
reader.onload = async (e) => { reader.onload = async (e) => {
const imageSrc = e.target?.result; 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]; const imageBase64 = (imageSrc as string).split(',')[1];
try { try {
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise(); const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
if (!response || !response.results) { if (!response || !response.results) {
this.processingStatus = 'Ungültige Antwort vom OCR-Service'; this.processingStatus = 'Invalid response from OCR service';
this.loading = false; this.loading = false;
return; return;
} }
this.processingStatus = 'Verarbeitung abgeschlossen'; this.processingStatus = 'Processing complete';
this.loading = false; this.loading = false;
// Emit Event mit Bilddaten und OCR-Ergebnissen // Emit event with image data and OCR results
const bildname=this.imageFile?.name??''; const imageName = this.imageFile?.name ?? '';
const bildid=response.results.length>0?response.results[0].name:null const imageId = response.results.length > 0 ? response.results[0].name : null;
const boxes:Box[] = []; const boxes: Box[] = [];
response.results.forEach((result: OcrResult) => { response.results.forEach((result: OcrResult) => {
const box = result.box; const box = result.box;
const xs = box.map((point: number[]) => point[0]); const xs = box.map((point: number[]) => point[0]);
const ys = box.map((point: number[]) => point[1]); const ys = box.map((point: number[]) => point[1]);
const xMin = Math.min(...xs); const xMin = Math.min(...xs);
const xMax = Math.max(...xs); const xMax = Math.max(...xs);
const yMin = Math.min(...ys); const yMin = Math.min(...ys);
const yMax = Math.max(...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.imageUploaded.emit({ imageSrc, deckImage });
this.resetFileInput(); this.resetFileInput();
// Schließe das Upload-Modal // Close the upload modal
this.closeModal(); this.closeModal();
} catch (error) { } catch (error) {
console.error('Fehler beim OCR-Service:', error); console.error('Error with OCR service:', error);
this.processingStatus = 'Fehler beim OCR-Service'; this.processingStatus = 'Error with OCR service';
this.loading = false; this.loading = false;
} }
}; };
reader.readAsDataURL(file); 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 { resetFileInput(): void {
if (this.imageFileElement && this.imageFileElement.nativeElement) { if (this.imageFileElement && this.imageFileElement.nativeElement) {
this.imageFileElement.nativeElement.value = ''; this.imageFileElement.nativeElement.value = '';
} }
} }
} }