GitHub Actions commited on
Commit
6b18c86
·
0 Parent(s):

Initial commit

Browse files
Files changed (8) hide show
  1. .env +1 -0
  2. .gitignore +3 -0
  3. Dockerfile +32 -0
  4. README.md +10 -0
  5. index.js +113 -0
  6. package.json +30 -0
  7. test.js +18 -0
  8. utils.js +245 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ GOOGLE_APPLICATION_CREDENTIALS_GENAI=AIzaSyBmQmBVKoOBsuP_ceBI9YGQUdUvvqSGA2E
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ node_modules/
2
+ *.log
3
+ *lock.json
Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:18-slim
2
+
3
+ # Install git and other dependencies as root user
4
+ RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
5
+
6
+ # Switch to the node user
7
+ USER node
8
+
9
+ # Set environment variables for the user
10
+ ENV HOME=/home/node \
11
+ PATH=/home/node/.local/bin:$PATH
12
+
13
+ # Set the working directory
14
+ WORKDIR $HOME/app
15
+
16
+ # Copy the package.json and package-lock.json files to the working directory
17
+ COPY --chown=node:node package*.json ./
18
+
19
+ # Install Node.js dependencies
20
+ RUN npm install
21
+
22
+ # Copy the application code to the working directory
23
+ COPY --chown=node:node . .
24
+
25
+ # Ensure the ownership of the directory to the node user
26
+ RUN chown -R node:node .
27
+
28
+ # Expose the port the app runs on
29
+ EXPOSE 7860
30
+
31
+ # Command to run the Node.js server
32
+ CMD ["node", "index.js"]
README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Wa Placement
3
+ emoji: 🏃
4
+ colorFrom: gray
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
index.js ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const { default: makeWASocket, useMultiFileAuthState, DisconnectReason, downloadMediaMessage } = require('@whiskeysockets/baileys');
3
+ const { Boom } = require('@hapi/boom');
4
+ const qrcode = require('qrcode-terminal');
5
+ const axios = require('axios');
6
+ const FormData = require('form-data');
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { writeFile } = require('fs/promises');
11
+
12
+ const { passtoGemini, passtoLENSOCR } = require("./utils");
13
+
14
+
15
+
16
+ // Create an instance of Express
17
+ const app = express();
18
+ const PORT = 7860;
19
+ var flag = false;
20
+
21
+ // Middleware to parse JSON
22
+ app.use(express.json());
23
+
24
+ // Define a sample route
25
+ app.get('/', (req, res) => {
26
+ res.send('Express server is running!');
27
+ });
28
+
29
+ // Start the Express server
30
+ app.listen(PORT, () => {
31
+ console.log(`Express server is running on http://localhost:${PORT}`);
32
+ });
33
+
34
+ async function startSock() {
35
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
36
+
37
+ const sock = makeWASocket({
38
+ auth: state,
39
+ printQRInTerminal: true,
40
+ });
41
+
42
+ sock.ev.on('creds.update', saveCreds);
43
+
44
+ sock.ev.on('connection.update', (update) => {
45
+ const { connection, lastDisconnect, qr } = update;
46
+ if (qr) {
47
+ qrcode.generate(qr, { small: true });
48
+ }
49
+ if (connection === 'close') {
50
+ const shouldReconnect = (lastDisconnect.error = Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
51
+ console.log('Connection closed due to', lastDisconnect.error, ', reconnecting', shouldReconnect);
52
+ // Reconnect if not logged out
53
+ if (shouldReconnect) {
54
+ startSock();
55
+ }
56
+ } else if (connection === 'open') {
57
+ console.log('Connected to WhatsApp');
58
+ }
59
+ });
60
+
61
+ sock.ev.on('messages.upsert', async (message) => {
62
+ try {
63
+ const msg = message.messages[0];
64
+ if (!msg.message) return;
65
+
66
+ console.log('Message:', msg.message.conversation);
67
+
68
+ if(msg.message.conversation.includes("/start")){
69
+ await sock.sendMessage(msg.key.remoteJid, { text: "Bot Started" });
70
+ flag = true;
71
+ return;
72
+ }
73
+
74
+ if(msg.message.conversation.includes("/stop")){
75
+ await sock.sendMessage(msg.key.remoteJid, { text: "Bot Stopped" });
76
+ flag = false;
77
+ return;
78
+ }
79
+
80
+
81
+ if(!flag){
82
+ return;
83
+ }
84
+
85
+ const messageType = Object.keys(msg.message)[0];
86
+
87
+ if (messageType === 'imageMessage') {
88
+ const sender = msg.key.participant || msg.key.remoteJid;
89
+
90
+ if (!fs.existsSync('./images')) {
91
+ fs.mkdirSync('./images');
92
+ }
93
+
94
+ var fileName = `./images/${Date.now()}_${sender.replace('@s.whatsapp.net', '')}`;
95
+ var extension = msg.message.imageMessage.mimetype.split('/')[1];
96
+ fileName = fileName + '.' + extension;
97
+
98
+ const buffer = await downloadMediaMessage(msg, 'buffer', {});
99
+ await writeFile(fileName, buffer);
100
+
101
+ var d = await passtoGemini(fileName);
102
+ var text = d.split("SPACESPACESPACE");
103
+
104
+ await sock.sendMessage(msg.key.remoteJid, { text: text[0] });
105
+ await sock.sendMessage(msg.key.remoteJid, { text: text[1] });
106
+ }
107
+ } catch (error) {
108
+ console.error('Error in m essage upsert:', error);
109
+ }
110
+ });
111
+ }
112
+
113
+ startSock();
package.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "whatsapp-bot",
3
+ "version": "1.0.0",
4
+ "description": "A WhatsApp bot using Baileys library",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "start": "node index.js"
8
+ },
9
+ "keywords": [
10
+ "whatsapp",
11
+ "bot",
12
+ "baileys"
13
+ ],
14
+ "author": "Your Name",
15
+ "license": "MIT",
16
+ "dependencies": {
17
+ "@google/generative-ai": "^0.19.0",
18
+ "@hapi/boom": "^10.0.1",
19
+ "@whiskeysockets/baileys": "^6.7.7",
20
+ "axios": "^1.7.7",
21
+ "chrome-lens-ocr": "^4.0.2",
22
+ "cors": "^2.8.5",
23
+ "dotenv": "^16.4.5",
24
+ "express": "^4.21.0",
25
+ "form-data": "^4.0.0",
26
+ "link-preview-js": "^3.0.5",
27
+ "markdown-it": "^14.1.0",
28
+ "qrcode-terminal": "^0.12.0"
29
+ }
30
+ }
test.js ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { passtoGemini, passtoLENSOCR } = require("./utils");
2
+
3
+
4
+
5
+ async function test(){
6
+
7
+
8
+ var d = await passtoLENSOCR("test.png");
9
+
10
+ // console.log(d.response.text());
11
+ console.log(d);
12
+
13
+
14
+
15
+ }
16
+
17
+
18
+ test();
utils.js ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const markdownIt = require('markdown-it');
3
+ const dotenv = require('dotenv');
4
+ const { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory } = require('@google/generative-ai');
5
+ dotenv.config();
6
+
7
+
8
+ const genAI = new GoogleGenerativeAI(process.env.GOOGLE_APPLICATION_CREDENTIALS_GENAI);
9
+
10
+
11
+ // Converts local file information to a GoogleGenerativeAI.Part object.
12
+ function fileToGenerativePart(path, mimeType) {
13
+ return {
14
+ inlineData: {
15
+ data: Buffer.from(fs.readFileSync(path)).toString("base64"),
16
+ mimeType
17
+ },
18
+ };
19
+ }
20
+
21
+
22
+ function generateHTMLFile(contentArray, outputFileName) {
23
+ const md = new markdownIt({
24
+ html: true,
25
+ linkify: true,
26
+ typographer: true,
27
+ });
28
+
29
+ let tabsNav = '';
30
+ let tabsContent = '';
31
+
32
+ // Loop through the content array to build tabs and content
33
+ contentArray.forEach((contentObj, index) => {
34
+ const tabId = 'tab' + index;
35
+ const tabName = contentObj.tabName || 'Tab ' + (index + 1);
36
+ const markdownContent = contentObj.content || '';
37
+ const htmlContentConverted = md.render(markdownContent);
38
+
39
+ // Build the tabs navigation buttons
40
+ tabsNav += `<button class="tablinks" onclick="openTab(event, '${tabId}')">${tabName}</button>`;
41
+
42
+ // Build the content for each tab
43
+ tabsContent += `<div id="${tabId}" class="tabcontent">${htmlContentConverted}</div>`;
44
+ });
45
+
46
+ // Assemble the final HTML content
47
+ const htmlContent = `
48
+ <!DOCTYPE html>
49
+ <html lang="en">
50
+ <head>
51
+ <meta charset="UTF-8">
52
+ <title>Tabbed Content</title>
53
+ <!-- Tailwind CSS CDN -->
54
+ <script src="https://cdn.tailwindcss.com"></script>
55
+ <!-- MathJax CDN -->
56
+ <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
57
+ <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
58
+ <style>
59
+ /* Style the tab links */
60
+ .tablinks {
61
+ @apply bg-gray-200 float-left border-none outline-none cursor-pointer py-2 px-4 transition duration-300 text-lg;
62
+ }
63
+ .tablinks:hover {
64
+ @apply bg-gray-300;
65
+ }
66
+ .tabcontent {
67
+ display: none;
68
+ padding: 1rem;
69
+ border-top: none;
70
+ }
71
+ .tabcontent {
72
+ animation: fadeEffect 1s;
73
+ }
74
+ @keyframes fadeEffect {
75
+ from {opacity: 0;}
76
+ to {opacity: 1;}
77
+ }
78
+ </style>
79
+ </head>
80
+ <body class="font-sans antialiased">
81
+
82
+ <div class="tab flex">
83
+ ${tabsNav}
84
+ </div>
85
+ <div class="tab-contents">
86
+ ${tabsContent}
87
+ </div>
88
+
89
+ <script>
90
+ function openTab(evt, tabId) {
91
+ var i, tabcontent, tablinks;
92
+ tabcontent = document.getElementsByClassName("tabcontent");
93
+ for (i = 0; i < tabcontent.length; i++) {
94
+ tabcontent[i].style.display = "none";
95
+ }
96
+ tablinks = document.getElementsByClassName("tablinks");
97
+ for (i = 0; i < tablinks.length; i++) {
98
+ tablinks[i].classList.remove("bg-blue-500", "text-white");
99
+ }
100
+ document.getElementById(tabId).style.display = "block";
101
+ evt.currentTarget.classList.add("bg-blue-500", "text-white");
102
+ }
103
+
104
+ // Open the first tab by default
105
+ document.addEventListener("DOMContentLoaded", function() {
106
+ document.querySelector('.tablinks').click();
107
+ });
108
+ </script>
109
+ </body>
110
+ </html>
111
+ `;
112
+
113
+ // Write the HTML content to the specified output file
114
+ fs.writeFileSync(outputFileName, htmlContent, 'utf8');
115
+
116
+ console.log(`HTML file "${outputFileName}" has been generated.`);
117
+ }
118
+
119
+
120
+ const ocr_prompt = `
121
+ Extract all readable text from the image, preserving the layout and formatting as closely as possible. Capture details such as:
122
+
123
+ All visible words, phrases, and sentences
124
+ Numbers, dates, or other numeric information
125
+ Special characters, including punctuation, currency symbols, and mathematical operators
126
+ Text orientation (horizontal, vertical, or rotated)
127
+ Any text embedded within logos, signs, or complex backgrounds Make sure to avoid any graphical elements and focus solely on text. Correctly identify letters with accents, diacritics, and special symbols. Ensure no part of the text is missed or misinterpreted
128
+ `;
129
+
130
+
131
+
132
+
133
+ function getGeminiModel(index) {
134
+ var models = [
135
+ 'gemini-1.5-pro-exp-0827',
136
+ 'gemini-1.5-pro',
137
+ 'gemini-1.5-flash',
138
+ ]
139
+
140
+ const safetySettings = [
141
+ {
142
+ category: HarmCategory.HARM_CATEGORY_HARASSMENT,
143
+ threshold: HarmBlockThreshold.BLOCK_NONE,
144
+ },
145
+ {
146
+ category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
147
+ threshold: HarmBlockThreshold.BLOCK_NONE,
148
+ },
149
+ {
150
+ category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
151
+ threshold: HarmBlockThreshold.BLOCK_NONE
152
+ },
153
+ {
154
+ category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
155
+ threshold: HarmBlockThreshold.BLOCK_NONE
156
+ }
157
+ ];
158
+
159
+ var modelname = models[index];
160
+ const model = genAI.getGenerativeModel({ model: modelname, safetySettings: safetySettings });
161
+
162
+ return model;
163
+ }
164
+
165
+
166
+
167
+ async function delay(ms) {
168
+ return new Promise(resolve => setTimeout(resolve, ms));
169
+ }
170
+
171
+ // Function to pass image to OCR
172
+ async function passtoLENSOCR(imagePath) {
173
+ try {
174
+ const { default: Lens } = await import("chrome-lens-ocr");
175
+ const lens = new Lens();
176
+ var data = await lens.scanByFile(imagePath);
177
+ data = data.segments.map((segment) => segment.text).join('\n');
178
+ return data;
179
+ } catch (e) {
180
+ console.log(e);
181
+ await delay(1500);
182
+ return passtoLENSOCR(imagePath);
183
+ }
184
+ }
185
+
186
+ async function getGeminiResponse(textContent) {
187
+ const prompt = `
188
+ solve the following question
189
+ ${textContent}
190
+ `;
191
+
192
+ const model = getGeminiModel(0);
193
+
194
+ const generatedContent = await model.generateContent([prompt]);
195
+
196
+ return generatedContent.response.text();
197
+ }
198
+
199
+
200
+ async function passtoGemini(imagePath) {
201
+
202
+ const imagePart = fileToGenerativePart(imagePath, "image/jpeg");
203
+
204
+ const model = getGeminiModel(0);
205
+
206
+
207
+ // const prompt = `
208
+ // Extract the entire question from the provided image and solve it. Return the result in the following JSON format, ensuring both the question and answer are formatted in Markdown for readability. Make sure the solution is accurate, clear, and concise.
209
+ // if its a coding question, provide the code in the answer section
210
+ // {
211
+ // "question": "Full question text extracted from the image in Markdown format",
212
+ // "response": "Comprehensive answer to the question in Markdown format",
213
+ // "answer":"ans"
214
+ // }
215
+
216
+ // Ensure all key details from the image are included in the extracted question.
217
+ // Solve the question clearly and provide a structured response using Markdown elements (like lists, code blocks, or math symbols if applicable).
218
+ // Format the output correctly in the specified JSON structure.
219
+ // `;
220
+
221
+ const prompt = `
222
+ Extract the entire question from the provided image and solve it.
223
+ if its a coding question, provide the code in the answer section in cpp language
224
+
225
+ provide the answer in a format specific to whatsapp application
226
+ provide a seperator "SPACESPACESPACE" space between the question and answer
227
+
228
+
229
+ `;
230
+
231
+ // const imageParts = [
232
+ // filePart1,
233
+ // filePart2,
234
+ // filePart3,
235
+ // ];
236
+ //for multiple images
237
+
238
+
239
+ const generatedContent = await model.generateContent([prompt, imagePart]);
240
+
241
+ return generatedContent.response.text();
242
+
243
+ }
244
+ //export functions
245
+ module.exports = { passtoGemini, generateHTMLFile, passtoLENSOCR };