Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
516 lines (442 loc) · 22.3 KB
/
Copy pathProgram.cs
File metadata and controls
516 lines (442 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using RecipesAIHelper.Data;
using RecipesAIHelper.Models;
using RecipesAIHelper.Services;
namespace RecipesAIHelper;
class Program
{
static async Task Main(string[] args)
{
// Check if running in console mode
if (args.Contains("--console"))
{
await RunConsoleMode(args);
return;
}
// Run web mode
await RunWebMode(args);
}
static async Task RunWebMode(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Configuration
builder.Configuration
.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
var openAiApiKey = builder.Configuration["OpenAI:ApiKey"] ??
Environment.GetEnvironmentVariable("OPENAI_API_KEY") ??
string.Empty;
var openAiModel = builder.Configuration["OpenAI:Model"] ?? "gpt-5-mini-2025-08-07";
var databasePath = builder.Configuration["Settings:DatabasePath"] ?? "recipes.db";
// Add services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Register services
builder.Services.AddSingleton(new RecipeDbContext(databasePath));
builder.Services.AddSingleton(new PdfImageService());
builder.Services.AddSingleton<AIServiceFactory>();
var app = builder.Build();
// Initialize database
var db = app.Services.GetRequiredService<RecipeDbContext>();
db.InitializeDatabase();
// Check if we need to migrate API keys from appsettings.json to database
var existingProviders = db.GetAllAIProviders();
if (existingProviders.Count == 0 && !string.IsNullOrEmpty(openAiApiKey) && openAiApiKey != "YOUR_OPENAI_API_KEY_HERE")
{
Console.WriteLine("📋 Migracja klucza OpenAI z appsettings.json do bazy danych...");
// Save API key to Settings table
db.UpsertSetting("OpenAI_ApiKey", openAiApiKey, "string", "Klucz API OpenAI (dla ekstrakcji przepisów i generowania obrazów)");
// Create AIProvider without API key (it will be fetched from Settings)
var openAiProvider = new AIProvider
{
Name = "OpenAI",
Model = openAiModel,
IsActive = true,
Priority = 10,
MaxPagesPerChunk = 3,
SupportsDirectPDF = true,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
db.InsertAIProvider(openAiProvider);
Console.WriteLine("✅ Klucz OpenAI zmigrowany do Settings, provider utworzony");
}
Console.WriteLine("=== Recipe AI Helper - Web Mode ===");
Console.WriteLine($"Database: {databasePath}");
Console.WriteLine($"Recipes in database: {db.GetRecipeCount()}");
// Check if API keys are configured
var activeProvider = db.GetActiveAIProvider();
if (activeProvider == null)
{
Console.WriteLine();
Console.WriteLine("⚠️ UWAGA: Brak skonfigurowanego providera AI");
Console.WriteLine(" Skonfiguruj klucze API w zakładce ⚙️ Ustawienia w interfejsie webowym");
}
else
{
Console.WriteLine($"Active AI Provider: {activeProvider.Name} ({activeProvider.Model})");
}
Console.WriteLine();
// Configure middleware
app.UseCors();
app.UseStaticFiles();
app.MapControllers();
// Fallback to index.html
app.MapFallbackToFile("index.html");
Console.WriteLine("🌐 Web interface available at:");
Console.WriteLine(" http://localhost:5000");
Console.WriteLine(" https://localhost:5001");
Console.WriteLine();
Console.WriteLine("Press Ctrl+C to stop");
await app.RunAsync("http://localhost:5000");
}
static async Task RunConsoleMode(string[] args)
{
Console.WriteLine("=== Recipe AI Helper - Console Mode ===\n");
// Load configuration
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables()
.Build();
var openAiApiKey = configuration["OpenAI:ApiKey"] ??
Environment.GetEnvironmentVariable("OPENAI_API_KEY") ??
string.Empty;
var openAiModel = configuration["OpenAI:Model"] ?? "gpt-5-nano-2025-08-07";
var pdfDirectory = configuration["Settings:PdfSourceDirectory"] ??
@"C:\Users\Karolina\Downloads\Dieta";
var databasePath = configuration["Settings:DatabasePath"] ?? "recipes.db";
var pagesPerChunk = int.TryParse(configuration["Settings:PagesPerChunk"], out var ppc) ? ppc : 4;
var delayBetweenChunks = int.TryParse(configuration["Settings:DelayBetweenChunksMs"], out var delay) ? delay : 3000;
var checkDuplicates = bool.TryParse(configuration["Settings:CheckDuplicates"], out var checkDup) ? checkDup : true;
var recentRecipesContext = int.TryParse(configuration["Settings:RecentRecipesContext"], out var recentCtx) ? recentCtx : 10;
Console.WriteLine($"Configuration:");
Console.WriteLine($" - OpenAI Model: {openAiModel}");
Console.WriteLine($" - Pages per chunk: {pagesPerChunk}");
Console.WriteLine($" - Delay between chunks: {delayBetweenChunks}ms");
Console.WriteLine($" - Check duplicates: {checkDuplicates}");
Console.WriteLine($" - Recent recipes context: {recentRecipesContext}");
// Initialize database
using var db = new RecipeDbContext(databasePath);
db.InitializeDatabase();
Console.WriteLine($"Database initialized: {databasePath}");
Console.WriteLine($"Current recipes in database: {db.GetRecipeCount()}\n");
// Show menu
while (true)
{
Console.WriteLine("\nChoose an option:");
Console.WriteLine("1. Process PDFs and extract recipes");
Console.WriteLine("2. Get random meal suggestions");
Console.WriteLine("3. View all recipes");
Console.WriteLine("4. Exit");
Console.Write("\nYour choice: ");
var choice = Console.ReadLine();
switch (choice)
{
case "1":
await ProcessPdfs(pdfDirectory, openAiApiKey, openAiModel, pagesPerChunk,
delayBetweenChunks, checkDuplicates, recentRecipesContext, db);
break;
case "2":
GetRandomMeals(db);
break;
case "3":
ViewAllRecipes(db);
break;
case "4":
Console.WriteLine("Goodbye!");
return;
default:
Console.WriteLine("Invalid choice. Try again.");
break;
}
}
}
static async Task ProcessPdfs(string pdfDirectory, string apiKey, string modelName, int pagesPerChunk,
int delayMs, bool checkDuplicates, int recentRecipesContext, RecipeDbContext db)
{
Console.WriteLine($"\n{'=',-80}");
Console.WriteLine($"ROZPOCZĘCIE PRZETWARZANIA PDF Z VISION API (1200 DPI → 2560px)");
Console.WriteLine($"{'=',-80}");
Console.WriteLine($"Folder: {pdfDirectory}");
Console.WriteLine($"Chunking: {pagesPerChunk} stron per chunk (render 1200 DPI → scale 2560px)");
Console.WriteLine($"Rate limiting: {delayMs}ms opóźnienia między chunkami");
Console.WriteLine($"Sprawdzanie duplikatów: {(checkDuplicates ? "TAK" : "NIE")}");
Console.WriteLine($"{'=',-80}\n");
var pdfImageService = new PdfImageService();
var openAiService = new OpenAIService(apiKey, modelName);
try
{
var pdfFiles = Directory.GetFiles(pdfDirectory, "*.pdf", SearchOption.AllDirectories).ToList();
Console.WriteLine($"📄 Znaleziono {pdfFiles.Count} plików PDF\n");
if (pdfFiles.Count == 0)
{
Console.WriteLine("❌ Brak plików PDF w katalogu.");
return;
}
var totalRecipesExtracted = 0;
var totalRecipesSaved = 0;
var totalDuplicatesSkipped = 0;
var totalChunksProcessed = 0;
var totalErrors = 0;
foreach (var pdfFile in pdfFiles)
{
Console.WriteLine($"\n{'=',-80}");
Console.WriteLine($"📋 Przetwarzanie: {Path.GetFileName(pdfFile)}");
Console.WriteLine($"{'=',-80}");
var fileRecipesExtracted = 0;
var fileRecipesSaved = 0;
var fileDuplicatesSkipped = 0;
try
{
// Render PDF pages at high DPI (1200) then scale down to 3200px for sharp output
var imageChunks = pdfImageService.RenderPdfInChunks(pdfFile, pagesPerChunk, dpi: 1200, saveDebugImages: true, targetHeight: 3200);
Console.WriteLine($"📊 PDF wyrenderowany w {imageChunks.Count} chunkach (1200 DPI → 3200px wysokość)\n");
// Track recipes already processed in THIS PDF to avoid duplicates within chunks
var processedInThisPdf = new List<string>();
for (int i = 0; i < imageChunks.Count; i++)
{
var imageChunk = imageChunks[i];
try
{
Console.WriteLine($"[Chunk {imageChunk.ChunkNumber}/{imageChunks.Count}] Strony {imageChunk.StartPage}-{imageChunk.EndPage}");
Console.WriteLine($" Liczba obrazów: {imageChunk.Pages.Count}");
// Get recent recipes for context (to avoid duplicates)
var recentRecipes = checkDuplicates
? db.GetRecentRecipes(recentRecipesContext)
: null;
if (recentRecipes != null && recentRecipes.Count > 0)
{
Console.WriteLine($" Kontekst: {recentRecipes.Count} ostatnich przepisów w bazie");
}
if (processedInThisPdf.Count > 0)
{
Console.WriteLine($" Historia PDF: {processedInThisPdf.Count} przepisów już przetworzonych w tym pliku");
}
// Send images to OpenAI Vision API for recipe extraction
Console.WriteLine($" ⏳ Wysyłanie obrazów do OpenAI Vision API ({modelName})...");
var startTime = DateTime.Now;
var recipes = await openAiService.ExtractRecipesFromImages(imageChunk, recentRecipes, processedInThisPdf);
var processingTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine($" ✅ Otrzymano {recipes.Count} przepisów (czas: {processingTime:F1}s)");
fileRecipesExtracted += recipes.Count;
// Save to database with duplicate checking
foreach (var recipeData in recipes)
{
try
{
// Validate recipe data
if (string.IsNullOrWhiteSpace(recipeData.Name))
{
Console.WriteLine($" ⚠️ Pominięto przepis bez nazwy");
continue;
}
if (recipeData.Ingredients == null || recipeData.Ingredients.Count == 0)
{
Console.WriteLine($" ⚠️ Pominięto '{recipeData.Name}' - brak składników");
continue;
}
// Check for duplicates
if (checkDuplicates)
{
if (db.RecipeExists(recipeData.Name))
{
Console.WriteLine($" ⏭️ Pominięto '{recipeData.Name}' - duplikat (dokładne dopasowanie)");
fileDuplicatesSkipped++;
continue;
}
var similarRecipe = db.FindSimilarRecipe(recipeData.Name, 0.8);
if (similarRecipe != null)
{
Console.WriteLine($" ⏭️ Pominięto '{recipeData.Name}' - podobny do '{similarRecipe.Name}'");
fileDuplicatesSkipped++;
continue;
}
}
// Save recipe
var recipe = new Recipe
{
Name = recipeData.Name,
Description = recipeData.Description,
Ingredients = string.Join("\n", recipeData.Ingredients),
Instructions = recipeData.Instructions,
Calories = recipeData.Calories,
Protein = recipeData.Protein,
Carbohydrates = recipeData.Carbohydrates,
Fat = recipeData.Fat,
MealType = Enum.TryParse<MealType>(recipeData.MealType, out var mealType)
? mealType
: MealType.Obiad,
CreatedAt = DateTime.Now,
NutritionVariants = recipeData.NutritionVariants
};
db.InsertRecipe(recipe);
Console.WriteLine($" ✅ Zapisano: {recipe.Name} ({recipe.MealType}) - {recipe.Calories} kcal");
fileRecipesSaved++;
// Add to processed list to prevent duplicates in subsequent chunks
processedInThisPdf.Add(recipe.Name);
}
catch (Exception ex)
{
Console.WriteLine($" ❌ Błąd zapisu '{recipeData.Name}': {ex.Message}");
totalErrors++;
}
}
totalChunksProcessed++;
// Progress indicator
var progress = (float)(i + 1) / imageChunks.Count * 100;
Console.WriteLine($" 📈 Postęp pliku: {progress:F0}%\n");
// Add delay between chunks to avoid rate limiting
if (i < imageChunks.Count - 1)
{
Console.WriteLine($" ⏸️ Oczekiwanie {delayMs}ms przed następnym chunkiem...\n");
await Task.Delay(delayMs);
}
}
catch (Exception ex)
{
Console.WriteLine($" ❌ Błąd przetwarzania chunku {imageChunk.ChunkNumber}: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($" Szczegóły: {ex.InnerException.Message}");
}
totalErrors++;
}
}
// File summary
Console.WriteLine($"\n{'─',-80}");
Console.WriteLine($"✅ Zakończono plik: {Path.GetFileName(pdfFile)}");
Console.WriteLine($" Chunków przetworzonych: {imageChunks.Count}");
Console.WriteLine($" Przepisów wyekstrahowanych: {fileRecipesExtracted}");
Console.WriteLine($" Przepisów zapisanych: {fileRecipesSaved}");
Console.WriteLine($" Duplikatów pominiętych: {fileDuplicatesSkipped}");
Console.WriteLine($"{'─',-80}\n");
totalRecipesExtracted += fileRecipesExtracted;
totalRecipesSaved += fileRecipesSaved;
totalDuplicatesSkipped += fileDuplicatesSkipped;
}
catch (Exception ex)
{
Console.WriteLine($"❌ Błąd przetwarzania pliku {Path.GetFileName(pdfFile)}: {ex.Message}");
totalErrors++;
}
}
// Final summary
Console.WriteLine($"\n{'=',-80}");
Console.WriteLine($"🎉 PRZETWARZANIE ZAKOŃCZONE");
Console.WriteLine($"{'=',-80}");
Console.WriteLine($"📁 Plików przetworzonych: {pdfFiles.Count}");
Console.WriteLine($"📦 Chunków przetworzonych: {totalChunksProcessed}");
Console.WriteLine($"📋 Przepisów wyekstrahowanych: {totalRecipesExtracted}");
Console.WriteLine($"✅ Przepisów zapisanych: {totalRecipesSaved}");
Console.WriteLine($"⏭️ Duplikatów pominiętych: {totalDuplicatesSkipped}");
Console.WriteLine($"❌ Błędów: {totalErrors}");
Console.WriteLine($"📊 Obecna liczba przepisów w bazie: {db.GetRecipeCount()}");
Console.WriteLine($"{'=',-80}");
}
catch (Exception ex)
{
Console.WriteLine($"❌ Krytyczny błąd: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"Szczegóły: {ex.InnerException.Message}");
}
}
}
static void GetRandomMeals(RecipeDbContext db)
{
Console.WriteLine("\n=== Plan Posiłków na Dziś ===\n");
try
{
var sniadanie = db.GetRandomRecipesByMealType(MealType.Sniadanie, 1);
var obiad = db.GetRandomRecipesByMealType(MealType.Obiad, 1);
var kolacja = db.GetRandomRecipesByMealType(MealType.Kolacja, 1);
if (sniadanie.Count > 0)
{
Console.WriteLine("ŚNIADANIE:");
PrintRecipe(sniadanie[0]);
}
else
{
Console.WriteLine("ŚNIADANIE: Brak przepisów w bazie danych");
}
if (obiad.Count > 0)
{
Console.WriteLine("\nOBIAD:");
PrintRecipe(obiad[0]);
}
else
{
Console.WriteLine("\nOBIAD: Brak przepisów w bazie danych");
}
if (kolacja.Count > 0)
{
Console.WriteLine("\nKOLACJA:");
PrintRecipe(kolacja[0]);
}
else
{
Console.WriteLine("\nKOLACJA: Brak przepisów w bazie danych");
}
// Calculate daily totals
var totalCalories = sniadanie.Sum(r => r.Calories) + obiad.Sum(r => r.Calories) + kolacja.Sum(r => r.Calories);
var totalProtein = sniadanie.Sum(r => r.Protein) + obiad.Sum(r => r.Protein) + kolacja.Sum(r => r.Protein);
var totalCarbs = sniadanie.Sum(r => r.Carbohydrates) + obiad.Sum(r => r.Carbohydrates) + kolacja.Sum(r => r.Carbohydrates);
var totalFat = sniadanie.Sum(r => r.Fat) + obiad.Sum(r => r.Fat) + kolacja.Sum(r => r.Fat);
Console.WriteLine("\n=== PODSUMOWANIE DNIA ===");
Console.WriteLine($"Kalorie: {totalCalories} kcal");
Console.WriteLine($"Białko: {totalProtein:F1}g");
Console.WriteLine($"Węglowodany: {totalCarbs:F1}g");
Console.WriteLine($"Tłuszcze: {totalFat:F1}g");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void ViewAllRecipes(RecipeDbContext db)
{
Console.WriteLine("\n=== All Recipes ===\n");
try
{
var recipes = db.GetAllRecipes();
if (recipes.Count == 0)
{
Console.WriteLine("No recipes in database yet. Process some PDFs first!");
return;
}
foreach (var recipe in recipes)
{
Console.WriteLine($"\n[{recipe.MealType}] {recipe.Name}");
Console.WriteLine($"Calories: {recipe.Calories} | P: {recipe.Protein}g | C: {recipe.Carbohydrates}g | F: {recipe.Fat}g");
Console.WriteLine(new string('-', 60));
}
Console.WriteLine($"\nTotal recipes: {recipes.Count}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void PrintRecipe(Recipe recipe)
{
Console.WriteLine($"{recipe.Name}");
Console.WriteLine($"Calories: {recipe.Calories} kcal | Protein: {recipe.Protein}g | Carbs: {recipe.Carbohydrates}g | Fat: {recipe.Fat}g");
if (!string.IsNullOrEmpty(recipe.Description))
{
Console.WriteLine($"Description: {recipe.Description}");
}
}
}