Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
aasthakourav20 committed Jun 13, 2024
0 parents commit 81fc91f
Show file tree
Hide file tree
Showing 88 changed files with 29,003 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
21 changes: 21 additions & 0 deletions .github/workflows/preview.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Vercel Preview Deployment
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
on:
push:
branches-ignore:
- main
jobs:
Deploy-Preview:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Vercel CLI
run: npm install --global vercel@latest
- name: Pull Vercel Environment Information
run: vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
- name: Build Project Artifacts
run: vercel build --token=${{ secrets.VERCEL_TOKEN }}
- name: Deploy Project Artifacts to Vercel
run: vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }}
21 changes: 21 additions & 0 deletions .github/workflows/production.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Vercel Production Deployment
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
on:
push:
branches:
- main
jobs:
Deploy-Production:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Vercel CLI
run: npm install --global vercel@latest
- name: Pull Vercel Environment Information
run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}
- name: Build Project Artifacts
run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}
- name: Deploy Project Artifacts to Vercel
run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.env
build
17 changes: 17 additions & 0 deletions Backend/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
GEMINI_KEY=
SERVER_PORT=8800
MONGO_URI=
WEBSOCKET_SERVER=
FIREBASE_KEY = '{
"type": "",
"project_id": "",
"private_key_id": "",
"private_key": "",
"client_email": "",
"client_id": "",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url": "",
"universe_domain": ""
}'
3 changes: 3 additions & 0 deletions Backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.env
firebase.json
140 changes: 140 additions & 0 deletions Backend/controllers/analysis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
const dotenv = require("dotenv");
dotenv.config();
const { startGeminiChat } = require("../gemini/chat.js");
const chatHistModel = require("../models/ChatHist.js");
const {
analysisReportPrompt,
analysisScorePrompt,
analysisKeywordsPrompt,
} = require("../gemini/analysisPrompts.js");

const Report = require("../models/Report.js");
const User = require("../models/User.js");

const doAnalysis = async (req, res) => {
try {
if (!req.userId) {
res.status(401).json({ Error: "UserId not found" });
return;
}
const userId = req.userId;
const analysis = await genAnalysis(userId);

if (analysis?.info === "nodata") {
res.status(200).json({ msg: "nochatdata" });
return;
}

const reportDatas = await Report.create({
userId: userId,
keywords: analysis.keywords,
analysis: analysis.report,
score: analysis.score,
});
try {
const user = await User.findOne({id : userId})
axios.post('https://brainbuddy-email-api.onrender.com/welcomeEmail',{
"emailId" : user.email,
"score" : analysis.score,
"analysis" : analysis.report,
"keywords" : analysis.keywords
})
} catch (error) {
console.log("error sending the message");
}
res.status(200).json({ data: reportDatas });
} catch (error) {
res.status(500).json({ msg: "Internal Server Error" });
}
};

const genAnalysis = async (userId) => {
try {
if (userId === undefined) {
// through err
return;
}
const foundHist = await chatHistModel
.find({ userId: userId })
.sort({ timestamp: 1 });

if (foundHist.length === 0) {
return { info: "nodata" };
}

let foundHistForGemini = [];
for (let conv of foundHist) {
foundHistForGemini.push({
role: "user",
parts: [
{
text: conv.prompt,
},
],
});
foundHistForGemini.push({
role: "model",
parts: [
{
text: conv.response,
},
],
});
}

// generate report
let chat = startGeminiChat(foundHistForGemini);
let result = await chat.sendMessage(analysisReportPrompt);
let response = await result.response;
let report = response.text();

// generate score
chat = startGeminiChat(foundHistForGemini);
result = await chat.sendMessage(analysisScorePrompt);
response = await result.response;
const score = response.text();

// generate keywords
chat = startGeminiChat(foundHistForGemini);
result = await chat.sendMessage(analysisKeywordsPrompt);
response = await result.response;
const keywordsResp = response.text();
const keywords = keywordsResp
.replace(/[^a-zA-Z0-9 \n]/g, "")
.trim()
.split("\n")
.map((kw) => kw.trim())
.filter(
(kw) =>
kw.length !== 0 &&
kw.toLowerCase() !== "keyword" &&
kw.toLowerCase() !== "keywords"
);
// console.log(keywords);

return { report, score, keywords };
} catch (error) {
console.error(error);
}
};

const getAnalysis = async (req, res) => {
// console.log(req.cookies);
try {
if (!req.userId) {
res.status(401).json({ msg: "UserId not found" });
return;
}
const userId = req.userId;

const reports = await Report.find({
userId: userId,
}).sort({ timestamp: -1 });

res.status(200).json({ data: reports });
} catch (error) {
res.status(500).json({ msg: "Internal Server Error" });
}
};

module.exports = { genAnalysis, doAnalysis, getAnalysis };
14 changes: 14 additions & 0 deletions Backend/controllers/article.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const dotenv = require("dotenv");
dotenv.config();
const { startGeminiChat } = require("../gemini/chat.js");

const fetchArticleFromKeywords = async (req, res) => {
try {
if (req.userId === undefined) {
// through err
return;
}
} catch (error) {}
};

module.exports = { fetchArticleFromKeywords };
115 changes: 115 additions & 0 deletions Backend/controllers/chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
const dotenv = require("dotenv");
const { v4: uuid } = require("uuid");
const WebSocket = require("ws");
const querystring = require("querystring");
dotenv.config();
const { startGeminiChat } = require("../gemini/chat.js");
const chatHistModel = require("../models/ChatHist.js");

const connectWithChatBot = async (req, res) => {
try {
if (req.userId === undefined) {
// through err
return;
}
const foundHist = await chatHistModel
.find({ userId: req.userId })
.sort({ timestamp: 1 });

// console.log(foundHist);

let foundHistForGemini = [];
for (let conv of foundHist) {
foundHistForGemini.push({
role: "user",
parts: [
{
text: conv.prompt,
},
],
});
foundHistForGemini.push({
role: "model",
parts: [
{
text: conv.response,
},
],
});
}
// console.log(foundHistForGemini[0]);

const roomId = uuid();
const websocketserverLink = `${String(
process.env.WEBSOCKET_SERVER
)}?${querystring.stringify({
id: roomId,
// serverkey: process.env.WEBSOCKET_SERVER_KEY,
isServer: true,
})}`;

const wss = new WebSocket(websocketserverLink);
wss.on("open", () => {
// console.log("opn");
res.status(200).json({ chatId: roomId });
wss.send(JSON.stringify({ type: "server:connected" }));
});

// Get history from mongo
const chat = startGeminiChat(foundHistForGemini);

wss.on("message", async (data) => {
try {
data = JSON.parse(data.toString());

if (data?.type === "client:chathist") {
wss.send(
JSON.stringify({ type: "server:chathist", data: foundHist })
);
} else if (data?.type === "client:prompt") {
if (data.prompt === undefined) {
// throw err
return;
}

// Prompt by the user sent to gemini
const result = await chat.sendMessageStream(data.prompt);
let respText = "";
wss.send(JSON.stringify({ type: "server:response:start" }));

for await (const chunk of result.stream) {
const chunkText = chunk.text();

wss.send(
JSON.stringify({
type: "server:response:chunk",
chunk: chunkText,
})
);
respText += chunkText;
}
wss.send(JSON.stringify({ type: "server:response:end" }));
// should be stored in the db
await chatHistModel.create({
userId: req.userId,
prompt: data.prompt,
response: respText,
});
}
} catch (error) {
console.log(error);
}
});
wss.on("close", () => {
// console.log("cls");
});
wss.on("error", (error) => {
console.error("WebSocket Error:", error.message);
res.sendStatus(404);
});
} catch (error) {
console.error(error);
res.sendStatus(404);
}
};
module.exports = { connectWithChatBot };
Loading

0 comments on commit 81fc91f

Please sign in to comment.