33import express , { Router } from "express" ;
44import formidable from "express-formidable" ;
55import bodyParserErrorHandler from "express-body-parser-error-handler" ;
6+ import fs from "fs" ;
67
78const { urlencoded, json } = express ;
89
@@ -31,6 +32,34 @@ const initServer = (model, serverName = "back-end") => {
3132 const router = Router ( ) ;
3233 app . use ( loggerMiddleware ( serverName ) ) ;
3334
35+ // In-memory storage for recent predictions (max 5)
36+ const recentPredictions = [ ] ;
37+
38+ // Helper function to add prediction to recent storage
39+ const addToRecentPredictions = ( result , imagePath , language ) => {
40+ try {
41+ const imageBase64 = fs . readFileSync ( imagePath , { encoding : 'base64' } ) ;
42+
43+ const predictionEntry = {
44+ id : Date . now ( ) + Math . random ( ) , // Simple unique ID
45+ predictions : result ,
46+ imageBase64,
47+ language,
48+ timestamp : new Date ( ) . toISOString ( )
49+ } ;
50+
51+ // Add to beginning of array
52+ recentPredictions . unshift ( predictionEntry ) ;
53+
54+ // Keep only the last 5 predictions
55+ if ( recentPredictions . length > 5 ) {
56+ recentPredictions . pop ( ) ;
57+ }
58+ } catch ( error ) {
59+ console . error ( 'Error saving to recent predictions:' , error ) ;
60+ }
61+ } ;
62+
3463 router . post ( "/api/upload/:language" , async ( req , res ) => {
3564 try {
3665 console . log ( `/api/upload/ ^ language=>${ req . params . language } ` ) ;
@@ -55,6 +84,10 @@ const initServer = (model, serverName = "back-end") => {
5584 null ,
5685 languageProvider
5786 ) ;
87+
88+ // Save to recent predictions
89+ addToRecentPredictions ( result , filePath , language ) ;
90+
5891 res . send ( result ) ;
5992 }
6093 }
@@ -85,6 +118,15 @@ const initServer = (model, serverName = "back-end") => {
85118 res . send ( { version : "1.0" } ) ;
86119 } ) ;
87120
121+ router . get ( "/api/recent-predictions" , async ( req , res ) => {
122+ try {
123+ res . send ( recentPredictions ) ;
124+ } catch ( err ) {
125+ console . error ( err ) ;
126+ res . status ( 500 ) . send ( "Something went wrong" ) ;
127+ }
128+ } ) ;
129+
88130 app . use ( urlencoded ( { extended : true } ) ) ;
89131 app . use ( json ( ) ) ;
90132 app . use ( formidable ( ) ) ;
0 commit comments