Skip to content

Commit

Permalink
ready
Browse files Browse the repository at this point in the history
  • Loading branch information
SarahAbuirmeileh committed Sep 2, 2023
1 parent 7f14c1c commit 917b146
Show file tree
Hide file tree
Showing 19 changed files with 308 additions and 8 deletions.
22 changes: 22 additions & 0 deletions db/dataSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { DataSource } from "typeorm";
import { Logger } from "./entities/logger.js";

const dataSource = new DataSource({
type: 'mysql',
host: 'geeky-scripters.ckxcq2pvrc9s.eu-west-2.rds.amazonaws.com',
port: 3306,
username: 'root',
password: '123456789',
database: 'Hackathon',
entities: [Logger],
synchronize: true,
logging: true
});

dataSource.initialize().then(() => {
console.log("Connected to DB!");
}).catch(err => {
console.error('Failed to connect to DB: ' + err);
});

export default dataSource;
19 changes: 19 additions & 0 deletions db/entities/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { BaseEntity, Column, CreateDateColumn, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class Logger extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;

@CreateDateColumn({
type: 'timestamp',
default: () => "CURRENT_TIMESTAMP(6)"
})
createdAt: Date;

@Column({length:5000, nullable:false})
result:string

@Column({ nullable:false})
imgPath:string
}
Binary file removed images/meme.jpg
Binary file not shown.
104 changes: 97 additions & 7 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,107 @@
import express from 'express'
import aws from 'aws-sdk'
import multer from 'multer';
import fs from 'fs'
import ObjectRouter from './routes/ObjectLable.js'
import celebrityRouter from './routes/celebrityFaces.js'
import textRouter from './routes/text.js'
import db from './db/dataSource.js'

aws.config.update({
region: 'us-west-2',
accessKeyId: 'AKIA3SQWPZW4XOFAUREH',
secretAccessKey: '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'
})

const s3 = new aws.S3();

s3.putObject({Bucket:"sarah-test-medium",Key:"images/meme.jpg"},(err,sucsess)=>{
if (err){
console.log(err)
}else{
console.log(sucsess)
const PORT = 3000;
const app = express()


app.use(express.json())
app.use('/ObjectLable',ObjectRouter)
app.use('/celebrityFaces',celebrityRouter)
app.use('/textDetection',textRouter)

const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'uploads/');
},
filename: (req, file, callback) => {
callback(null, file.originalname)
}
})
});
const upload = multer({ storage });



app.listen(PORT, () => {
console.log(`App is running and Listening on port ${PORT}`);
db.initialize()
});


// app.post('/upload', upload.single('file'), async (req, res) => {
// if (!req.file) {
// return res.status(500).send("Failed to upload file!");
// }

// const params = {
// Image: {
// Bytes: req.file.buffer, // Use the buffer from the uploaded file
// },
// };

// try {
// const data = await rekognition.detectLabels(params).promise();
// console.log('Detected labels:', data.Labels);
// const dataLabels = data.Labels.map(label => label.Name); // Extract label names
// res.status(201).json({ labels: dataLabels });
// } catch (err) {
// console.error('Error detecting labels:', err);
// res.status(500).send("Failed to detect labels");
// }
// });








// app.get('/file', (req:any, res) => {
// const fileName = req.query.name?.toString() || '';
// try {
// const data = fs.readFileSync('uploads/' + fileName, 'utf-8');
// const JSONData = JSON.parse(data) as any[];
// console.log("-----------------------");
// console.log(JSONData[0].author);
// console.log("-----------------------");
// res.send(JSONData);
// } catch (error) {
// console.error(error);
// res.status(500).send("Something went wrong");
// }
// });




// const s3 = new aws.S3();

// const rekognition = new aws.Rekognition();

// const params = {
// Image: {
// S3Object: {
// Bucket: 'sarah-test-medium',
// Name: 'images/meme.jpg',
// },
// },
// };

// rekognition.detectFaces(params, (err, data) => {
// if (err) console.error(err);
// else console.log(data);
// });
54 changes: 54 additions & 0 deletions routes/ObjectLable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import aws from 'aws-sdk'
import express from 'express'
import multer from 'multer';
import fs from 'fs'
import rekognition from 'aws-sdk/clients/rekognition.js';
import { Any } from 'typeorm';
import { Logger } from '../db/entities/logger.js';

const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'uploads/');
},
filename: (req, file, callback) => {
callback(null, Date.now() + '-' + file.originalname)
}
});
const upload = multer({ storage });

const router = express.Router()
router.post('/', upload.single('file'), async (req, res) => {
if (!req.file) {
res.status(500).send("Failed Upload File!");
return;
}
const imagePath = 'uploads/dad.jpeg';
const imageBuffer = fs.readFileSync(imagePath);
const params = {
Image: {
Bytes: imageBuffer,
},
};
let dataLable;
const rekognition = new aws.Rekognition();

try {
const data = await rekognition.detectLabels(params).promise();
console.log('Detected labels:', data.Labels);
const dataLabels = data.Labels?.map(label => label.Name); // Extract label names

const newLogger = new Logger();
newLogger.result = await JSON.stringify(dataLabels);
newLogger.imgPath = imagePath;
await newLogger.save()

res.status(201).json({ labels: dataLabels });
} catch (err) {
console.error('Error detecting labels:', err);
res.status(500).send("Failed to detect labels");
}

});


export default router
57 changes: 57 additions & 0 deletions routes/celebrityFaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import aws from 'aws-sdk';
import express from 'express';
import multer from 'multer';
import fs from 'fs';
import { Logger } from '../db/entities/logger.js';

const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'uploads/');
},
filename: (req, file, callback) => {
callback(null,file.originalname);
},
});
const upload = multer({ storage });

const router = express.Router();

router.post('/', upload.single('file'), async (req, res) => {
if (!req.file) {
res.status(500).send("Failed Upload File!");
return;
}

const imagePath = req.file.path; // Use the uploaded image path
const imageBuffer = fs.readFileSync(imagePath);

const rekognition = new aws.Rekognition();

const params = {
Image: {
Bytes: imageBuffer,
},
};

try {
const data = await rekognition.recognizeCelebrities(params).promise();
console.log('Detected celebrities:', data.CelebrityFaces);

const celebrities = data.CelebrityFaces?.map((celebrity) => ({
name: celebrity.Name,
confidence: celebrity.MatchConfidence,
}));

const newLogger= new Logger();
newLogger.result= await JSON.stringify(celebrities);
newLogger.imgPath=imagePath;
await newLogger.save()

res.status(201).json({ celebrities });
} catch (err) {
console.error('Error recognizing celebrities:', err);
res.status(500).send("Failed to recognize celebrities");
}
});

export default router;
58 changes: 58 additions & 0 deletions routes/text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import aws from 'aws-sdk';
import express from 'express';
import multer from 'multer';
import fs from 'fs';
import { Logger } from '../db/entities/logger.js';

const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'uploads/');
},
filename: (req, file, callback) => {
callback(null, Date.now() + '-' + file.originalname);
},
});
const upload = multer({ storage });

const router = express.Router();

router.post('/', upload.single('file'), async (req, res) => {
if (!req.file) {
res.status(500).send("Failed Upload File!");
return;
}

const imagePath = req.file.path; // Use the uploaded image path
const imageBuffer = fs.readFileSync(imagePath);

const rekognition = new aws.Rekognition();

const params = {
Image: {
Bytes: imageBuffer,
},
};

try {
const data = await rekognition.detectText(params).promise();
console.log('Detected text:', data.TextDetections);

const detectedText = data.TextDetections?.map((textDetection) => ({
detectedText: textDetection.DetectedText,
confidence: textDetection.Confidence,
boundingBox: textDetection.Geometry?.BoundingBox,
}));

const newLogger = new Logger();
newLogger.result = await JSON.stringify(detectedText);
newLogger.imgPath = imagePath;
await newLogger.save()

res.status(201).json({ detectedText });
} catch (err) {
console.error('Error detecting text:', err);
res.status(500).send("Failed to detect text");
}
});

export default router;
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"target": "es2018", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
Expand Down
Binary file added uploads/1693647646663-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693647819657-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693649144587-dad.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693649201460-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693649280286-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693649345091-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693649391315-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693650428947-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/1693650447851-text.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/Harry_Potter.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/dad.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 917b146

Please sign in to comment.