Coder Social home page Coder Social logo

pawanosman / googlebard Goto Github PK

View Code? Open in Web Editor NEW
410.0 7.0 58.0 80 KB

GoogleBard - A reverse engineered API for Google Bard chatbot for NodeJS

Home Page: https://bard.google.com

License: MIT License

TypeScript 100.00%
chatgpt google google-bard ai assistant assistant-chat-bots api prompt reverse-engineering scraping

googlebard's Introduction

GoogleBard

An NPM module for creating GoogleBard chatbot using Bard's reverse-engineered API. With reverse-engineered API functionalities, it empowers developers to harness the full potential of Bard.


npm version GitHub issues GitHub forks

Table Of Contents


Features

  • Simulating Response Streaming: The package simulates response streaming, allowing you to get the response as soon as it is available.
  • Multiple Conversations: The package supports multiple conversations, allowing you to have multiple parallel conversations with the chatbot.
  • Proxy Support: The package supports proxies, allowing you to use the chatbot from any location.
  • Lightweight: The package is very lightweight, making it easy to use and integrate into your projects.

Prerequisite - How to get cookies?*

  1. Install Cookie-Editor extension.
  2. Go to https://bard.google.com and login.
  3. Click on the extension icon and copy a cookie starting with __Secure-{account_number}PSID.
    • For example, __Secure-1PSID
    • Ensure you are copying the correct cookie corresponding to the account number, which can be found in the URL as bard.google.com/u/{account_number}.
    • If your account number is /u/2, search for the cookie named __Secure-2PSID.
    • If your account number is /u/3, search for the cookie named __Secure-3PSID.
  4. Paste the cookie in your code.

Installation

To install the package, run the following command:

npm install googlebard

Documentation

1. How To Initialise The Bot?

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies);

// other code - scroll below to view different functionalities available

2. How To Configure Bot With Optional Settings?

  1. inMemory: optional - if true will not save conversations to disk
  2. savePath: optional - path to save conversations (e.g './conversations.json')
  3. proxy: optional - handles proxy configurations
import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
    inMemory: false,
	savePath: "./conversations.json",
	proxy: {
		host: process.env.PROXY_HOST,
		port: process.env.PROXY_PORT,
		auth: {
			username: process.env.PROXY_USERNAME,
			password: process.env.PROXY_PASSWORD,
		},
		protocol: "http",
	},
});

// other code

3. How To Ask Bot?

To ask bot questions, you may use the bot.ask(<prompt>, <conversation_id>:optional) functionality. A usage of it is given below:

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies);
let conversationId = "some_random_id"; // optional: to make it remember the conversation

let response = await bot.ask("What is my name?", conversationId); // conversationId is optional
console.log(response);
>> I don't know your name. I am a large language model, also known as a conversational AI or cha...

Using the same conversation_id again will allow the bot to remember what you said earlier in the conversation
import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
    inMemory: false,
    savePath: "./conversations.json", // this is being done to save crucial information about the conversation so the bot remembers it
});

let conversationId = "test_id";

let response = await bot.ask("My name is Mehul", conversationId);
console.log(response);
>> Hi Mehul, it's nice to meet you! I'm Bard...
import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
    inMemory: false,
    savePath: "./conversations.json",
});

let conversationId = "test_id";

let response = await bot.ask("What is my name?", conversationId)
console.log(response);
>> I know your name is Mehul. You told me earlier.

4. How To Ask Bot And Simulate Response Streaming?

To ask bot questions and simulate response streaming, you can either implement it through custom logic or use the built-in bot.askStream(<callback>, <content>, <conversation_id>:optional). A usage of it is given below:

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
    inMemory: false,
    savePath: "./conversations.json",
});
let conversationId = "test_id";

await bot.askStream(
	(res) => {
		console.log(res);
	}, // returns the response
	"Hello?",
	conversationId,
);
>> Your 
name 
is 
Mehul. 
I 
will 
remember 
that 
for 
the
next 
time 
we 
speak.
Response streaming functionality is used to show as if the bot itself is typing

5. How To Reset A Conversation?

To reset a conversation, you may use the bot.resetConversation(<conversation_id>) functionality. This functionality allows the user to make the bot forget about previous conversations provided they are all under the same conversation_id. A usage of it is given below:

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
  inMemory: false,
  savePath: "./conversations.json",
});

let conversationId = "test_id"; // notice id is the same as that used in the above example

let response = await bot.ask("what is my name?", conversationId);
console.log(response);
>> You told me your name is Mehul.
import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
  inMemory: false,
  savePath: "./conversations.json",
});

let conversationId = "test_id";
bot.resetConversation(conversationId) // resetting conversation

let response = await bot.ask("what is my name?", conversationId);
console.log(response);
>> I understand that you are trying to get me to say your name, but...

6. How To Get All Your Previous Conversations?

In order to retrieve all your conversations, you may either implement the functionality through a custom logic or simply use the built-in bot.getAllConversations(). .A usage of it is given below:

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
	savePath: "./conversations.json",
});

let response = bot.getAllConversations()
console.log(response) // returns an array of different conversations

7. How To Get A Single Conversation By ID?

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
  inMemory: false,
  savePath: "./conversations.json",
});
let conversationId = "test_id";

await bot.waitForLoad();
let response = bot.getConversationById(conversationId);
console.log(response); // returns an object

Examples

A simple example has been added to the examples directory which shows how GoogleBard can be used to create a CLI chatbot. More such examples are yet to be added, so stay tuned!

googlebard's People

Contributors

jose-rojas-nebulosa avatar mehul-srivastava avatar pawanosman avatar w3bdesign avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

googlebard's Issues

Problem opening inMemory

const bardUnofficalChat=async (req,res)=>{
let {message}=req.body
const {Bard} = await import("googlebard")

let cookies = __Secure-1PSID=${process.env.BARD_AUTH};

let bot = new Bard(cookies, {
inMemory: false, // optional: if true, it will not save conversations to disk
savePath: "./chatjson/conversations.json", // optional: path to save conversations
});

let conversationId = "conversation name"; // optional: to make it remember the conversation

// let response = await bot.ask(message); // conversationId is optional
// console.log(response);
// res.json({
// data:response
// })

// Simulating response streaming
await bot.askStream(
(res) => {
console.log(res);
},
message,
// conversationId,
);
}

module.exports={
bardUnofficalChat
}

I ran the above code and found that adding {
inMemory: false, // optional: if true, it will not save conversations to disk
savePath: "./chatjson/conversations.json", // optional: path to save conversations
} With this code, node will be restarted due to changes in the file, resulting in the inability to output chat messages. Then I configure { in nodemon.json
"ignore": [
"chatjson/*"
]
}
It doesn't work either, do you guys know how to solve it?

ReactJS/NextJS Project: Module not found: Can't resolve 'fs'

Issue:

wait  - compiling...
event - compiled client and server successfully in 914 ms (307 modules)
wait  - compiling / (client and server)...
error - ./node_modules/dbcontext/dist/classes/dbcontext.js:1:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/dbcontext/dist/index.js
./node_modules/googlebard/dist/classes/app-dbcontext.js
./node_modules/googlebard/dist/classes/bard.js
./node_modules/googlebard/dist/index.js
./components/chat/messages.tsx
./pages/index.tsx

https://nextjs.org/docs/messages/module-not-found
Could not find files for / in .next/build-manifest.json
Could not find files for / in .next/build-manifest.json

Major Packages installed:

    "fs": "0.0.1-security",
    "googlebard": "^1.0.5",
    "next": "^12.0.9",
    "react": "17.0.2",
    "react-dom": "17.0.2",

SNlM0e does not seem to be present when being fetched

I was trying to use this package (well done btw), and it kept not working, so I decided to look into the code, and found that SNlM0e does not seem to be there (in the html data) when being fetched? It could just be something on my side, please look into it, many thanks.

Traceback

Hi if have this error:

Traceback (most recent call last):
  File "v:\Abschluss_V4\main.py", line 75, in <module>
    main()
  File "v:\Abschluss_V4\main.py", line 71, in main
    response = prompt_bard(prompt_text)
  File "v:\Abschluss_V4\main.py", line 24, in prompt_bard
    response = chatbot.ask(prompt)
  File "C:\Users\Olive\AppData\Roaming\Python\Python310\site-packages\Bard.py", line 132, in ask
    "content": json_chat_data[0][0],
TypeError: 'NoneType' object is not subscriptable

Here is my code/project:

from Bard import Chatbot
from playsound import playsound
import speech_recognition as sr
from os import system
import whisper
import warnings
import sys

token = 'YOUR TOKEN'
chatbot = Chatbot(token)
r = sr.Recognizer()

tiny_model = whisper.load_model('tiny')
base_model = whisper.load_model('base')
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using Fp32 instead")

if sys.platform != 'darwin':
    import pyttsx3
    engine = pyttsx3.init()
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate-50)

def prompt_bard(prompt):
    response = chatbot.ask(prompt)
    return response['content']

def speak(text):
    if sys.platform == 'darwin':
        ALLOWED_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?!-_$: ")
        clean_text = ''.join(c for c in text if c in ALLOWED_CHARS)
        system(f"sys '{clean_text}'")
    else:
        engine.say(text)
        engine.runAndWait()
        
def main():
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        while True:
            while True:
                try:
                    print('\n Say "hey" to wake me up. \n"')
                    audio = r.listen(source)
                    with open("wake_detect.wav", "wb") as f:
                        f.write(audio.get_wav_data())
                    result = tiny_model.transcribe('wake_detect.wav')
                    text_input = result['text']
                    if 'hey' in text_input.lower().strip():
                        break
                    else:
                        print("No wake word found. Try again.")
                except Exception as e:
                    print("Error transcibing audio: ", e)
                    continue
            try:
                playsound('wake_detected.mp3')
                print("Wake word detected. Please speak your prompt to Bard \n")
                audio = r.listen(source)
                with open("prompt.wav", "wb") as f:
                    f.write(audio.get_wav_data())
                result = base_model.transcribe('prompt.wav')
                prompt_text = result['text']
                print("Sending to Bard: ", prompt_text, '\n')
                if len(prompt_text.strip()) == 0:
                    print("Empty prompt. Please speak again.")
                    speak("Empty prompt. Please speak again.")
                    continue
            except Exception as e:
                print("Error transcribing audio: ", e)
                continue
            response = prompt_bard(prompt_text)
            speak(response)

if __name__ == '__main__':
    main()

ERR_REQUIRE_ESM

project/node_modules/ts-node/dist/index.js:851
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module

The proxy does not work

I install proxies as shown in the example, but they don't work. I used a proxy for bing and they work 100%. On replit, I insert only cookies and it works, I connect a proxy, and the proxy does not work on replit either. The error is definitely not in the proxy and not in the cookies, because they work separately. Cookies from usa

Confirmation of validity

Can you call the chat and use it normally now? Now report this problem Error parsing response: make sure you are using the correct cookie, copy the value of "__Secure-1PSID" cookie and set it like this:

new Bard("__Secure-1PSID=<COOKIE_VALUE>")

Also using a US proxy is recommended.

If this error persists, please open an issue on github.
The cookie setting is correct, and the network environment is also set up. Before, you can successfully receive chat replies, but now you can’t

How to use contextual dialogue

Hello, this is my case of trying to use contextual dialog:

const  chatjson=require('../../chatjson/conversations.json')

const bardUnofficalChat=async (req,res)=>{
      let {message,isfirst}=req.body
      const {Bard} = await import("googlebard")

let cookies = `__Secure-1PSID=${process.env.BARD_AUTH}`;

let bot = new Bard(cookies, {
	inMemory: false, // optional: if true, it will not save conversations to disk
	savePath: "./chatjson/conversations.json", // optional: path to save conversations
	// proxy: {
	// 	// optional: proxy configuration
	// 	host: process.env.PROXY_HOST,
	// 	port: process.env.PROXY_PORT,
	// 	auth: {
	// 		username: process.env.PROXY_USERNAME,
	// 		password: process.env.PROXY_PASSWORD,
	// 	},
	// 	protocol: "http",
	// },
});

let conversationId = ''; // optional: to make it remember the conversation
if(isfirst){
	conversationId=Date.now()
}else{
	conversationId=chatjson.conversations.rows[chatjson.conversations.rows.length-1].id
}



let response = await bot.ask(message,conversationId); // conversationId is optional
console.log(response);
res.json({
    data:response
})

// Simulating response streaming
// await bot.askStream(
// 	(res) => {
// 		console.log(res);
// 	},
// 	message,
// 	conversationId,
// );
}

module.exports={
    bardUnofficalChat
}

But it is not possible to carry out contextual dialogue. Please tell me how to use the correct usage. The cases in the document are not very clear.

TypeError: Cannot read properties of undefined (reading '0')

Hello, I'm not sure what happened, but after using this fine for a month or so all of a sudden, I keep getting the following error. Also as an attachment is a response for the request (cookie censored), using node 18.16.0 with googlebard 1.0.6

response.txt

file:///root/nodejs/yetanotherbot/node_modules/googlebard/dist/classes/bard.js:175
return resData[0];
^

TypeError: Cannot read properties of undefined (reading '0')
at Bard.ask (file:///root/nodejs/yetanotherbot/node_modules/googlebard/dist/classes/bard.js:175:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async file:///root/nodejs/yetanotherbot/aiHelper.js:58:21

Have issues requesting a prompt

import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';
import { Bard } from "googlebard";

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

app.get('/', async (req, res) => {
  res.status(200).send({
    message: '- Last Update May 17, 2023',
  })
});

app.post('/', async (req, res) => {

  try {

    const prompt = req.body.prompt;

    let cookies = `__Secure-1PSID=<i insert my token here>`;

    let bot = new Bard(cookies);
    
    let response = await bot.ask(prompt);
    console.log(response);
    

    res.status(200).send({
      bot: response
    });

  } catch (error) {
    res.status(500).send(error || 'Something went wrong, please try again.');
  }

})

app.listen(5500, () => console.log('Started on port 5500'))

Where i get the key? Inside this..
image

Sample json request:

{
  "prompt": "Hello"
}

Error:
image

Using proxy doesn't make any sense if the token you got is whitelisted and also i am able to use bard even i am not in US without using VPN.

Error when import {Bard} is ts file

E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:851
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\lab\node\line-chatgpt\node_modules\googlebard\dist\index.js from E:\lab\node\line-chatgpt\src\index.ts not supported.
Instead change the require of index.js in E:\lab\node\line-chatgpt\src\index.ts to a dynamic import() which is available in all CommonJS modules.
at Object.require.extensions. [as .js] (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:851:20)
at Object. (E:\lab\node\line-chatgpt\src\index.ts:21:18)
at Module.m._compile (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:857:29)
at Object.require.extensions. [as .ts] (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:859:16)
at phase4 (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:466:20)
at bootstrap (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:54:12)
at main (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:33:12)
at Object. (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:579:5) {
code: 'ERR_REQUIRE_ESM'
}

Can't run in browser with NextJS

./node_modules/.pnpm/[email protected]/node_modules/dbcontext/dist/classes/dbcontext.js:1:0
Module not found: Can't resolve 'fs'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/.pnpm/[email protected]/node_modules/dbcontext/dist/index.js
./node_modules/.pnpm/[email protected]/node_modules/googlebard/dist/classes/app-dbcontext.js
./node_modules/.pnpm/[email protected]/node_modules/googlebard/dist/classes/bard.js
./node_modules/.pnpm/[email protected]/node_modules/googlebard/dist/index.js
./src/agents/babyagi/bard.ts
./src/agents/babyagi/service.ts
./src/agents/babyagi/index.ts
./src/components/Agent/Agent.tsx
./src/pages/index.tsx

The fs module doesn't exist in browser contexts. Maybe we could not import dbcontext if inMemory is true?

Request fails without the __Secure-1PSIDTS cookie

The value of __Secure-1PSIDTS (or __Secure-2PSIDTS, __Secure-3PSIDTS, etc, depending on the user number) must be included in the cookie. This is what the cookies variable should look like in order to make a successful request:

let cookies = `__Secure-1PSID=<COOKIE_VALUE>; __Secure-1PSIDTS=<COOKIE_VALUE>`;

When it is not included (as described in the current readme) the request fails with this error:

Error parsing response: make sure you are using the correct cookie, copy the value of "__Secure-1PSID" cookie and set it like this:

new Bard("__Secure-1PSID=<COOKIE_VALUE>")

Also using a US proxy is recommended.

If this error persists, please open an issue on github.
https://github.com/PawanOsman/GoogleBard
file:///C:/Users/user/Source/bard-test/node_modules/googlebard/dist/classes/bard.js:174
        return resData[3];
                      ^

TypeError: Cannot read properties of undefined (reading '3')
    at Bard.ask (file:///C:/Users/user/Source/bard-test/node_modules/googlebard/dist/classes/bard.js:174:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async file:///C:/Users/user/Source/bard-test/index.js:8:16

How to get the cookie

Hello, thank you for the help, because it's really helpful. I want to know how to get the cookie, directly with a code, if you an astuce, because, the problem, is that the cookie cannot work sometimes and for a long term project, it's not easy to always put it manually.

Thanks for the help

Empty response when the query includes a url

The response is empty when the query includes a link to a webpage. For example try this query:

Can you summarize this article for me? https://blog.google/technology/ai/code-with-bard/

This happens because resData[3] contains an empty string. To get the actual response text the ask method needs to be modified to return resData[1]:

    async ask(prompt, conversationId) {
        let resData = await this.send(prompt, conversationId);
        return resData[3].length > 0 ? resData[3] : resData[1];
    }

Proxy error

Hello!

I recently encountered an issue while using proxies, specifically with Axios. I'm fairly confident that I've set up my proxy correctly, but I'm unsure if the problem lies with Axios itself or if there's a misconfiguration with my proxy.

The issue arose when using the default settings:

const agent = new https.Agent({
            rejectUnauthorized: false,
        });
        let axiosOptions = {
            proxy: this.options.proxy,
            httpsAgent: agent,
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0",
                Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate, br",
                Connection: "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "none",
                "Sec-Fetch-User": "?1",
                TE: "trailers",
            },
        };

With these settings, I received a 502 error, which stated "The requested URL could not be retrieved". This issue seemed to occur when using a Squid proxy.

To rectify this problem, I implemented the following steps:

  • 1: I used the HttpsProxyAgent() from the https-proxy-agent module.
  • 2: I removed the proxy setting.
  • 3: I set the httpsAgent with the HttpsProxyAgent.

Here's an example of the changes I made:

import HttpsProxyAgent from "https-proxy-agent";
let axiosOptions = {
          proxy: false,
          httpsAgent: new HttpsProxyAgent(`http://user:password@ip:port`),
          headers: {
              "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0",
              Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
              "Accept-Language": "en-US,en;q=0.5",
              "Accept-Encoding": "gzip, deflate, br",
              Connection: "keep-alive",
              "Upgrade-Insecure-Requests": "1",
              "Sec-Fetch-Dest": "document",
              "Sec-Fetch-Mode": "navigate",
              "Sec-Fetch-Site": "none",
              "Sec-Fetch-User": "?1",
              TE: "trailers",
          },
};

I suspect the issue may be a bug with Axios, possibly related to its handling of proxying HTTP to HTTPS. Alternatively, it might be a configuration issue with the Squid proxy. I thought it would be worth raising this issue to bring it to attention.

API gives unexpected/bad responses

Starting today, the bot's answers became dull and unintelligent, replying with the same prompt that was given or fragments of the prompt.

Example:

import { Bard } from "googlebard";

let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
    inMemory: false,
    savePath: "./conversations.json",
});

let conversationId = "test_id";

let response = await bot.ask("My name is Mehul", conversationId);
console.log(response);
>> Mehul

The issue persists after the module is reinstalled and also after the conversation is reset. Updating the cookie ID didn't help either. It used to work perfectly, this issue started presenting itself just today.

Google Bard encountered an error

Hi;

I was using the AI to make a Voice Assistant but encounter an error Below you can find my py file:

Google Bard encountered an error: b')]}'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n56\n[["di",58],["af.httprm",58,"-8469647117787525651",16]]\n25\n[["e",4,null,null,131]]\n'.

from Bard import Chatbot
from playsound import playsound
import speech_recognition as sr
from os import system
import whisper
import warnings
import sys

token = "YOUR TOKEN"
chatbot = Chatbot(token)
r = sr.Recognizer()

tiny_model = whisper.load_model('tiny')
base_model = whisper.load_model('base')
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")

if sys.platform != 'darwin':
import pyttsx3
engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-50)

def prompt_bard(prompt):
response = chatbot.ask(prompt)
return response['content']

def speak(text):
if sys.platform == 'darwin':
ALLOWED_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?!-_$: ")
clean_text = ''.join(c for c in text if c in ALLOWED_CHARS)
system(f"say '{clean_text}'")
else:
engine.say(text)
engine.runAndWait()

def main():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
while True:
while True:
try:
print('\nSay "google" to wake me up. \n')
audio = r.listen(source)
with open("wake_detect.wav", "wb") as f:
f.write(audio.get_wav_data())
result = tiny_model.transcribe('wake_detect.wav')
text_input = result['text']
if 'google' in text_input.lower().strip():
break
else:
print("No wake word found. Try again.")
except:
print("Error transcribe audio: ", e)
continue
try:
playsound('wake_detected.mp3')
print("Wake word detected. Please speak your prompt to Bard. \n")
audio = r.listen(source)
with open("prompt.wav", "wb") as f:
f.write(audio.get_wav_data())
result = base_model.transcribe('prompt.wav')
prompt_text = result['text']
print("Sending to Bard:", prompt_text, '\n')
if len(prompt_text.strip()) == 0:
print("Empty prompt. Please speak again.")
speak("Empty prompt. Please speak again.")
continue
except Exception as e:
print("Error transcribing audio: ", e)
continue
response = prompt_bard(prompt_text)
if sys.platform.startswith('win'):
print('Bards response: ', response)
else:
print('Bards response: ', response)
speak(response)

if name == 'main':
main()

not support CommonJS

/home/runner/bard/index.js:1
const Bard = require('googlebard')
^

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/runner/bard/node_modules/googlebard/dist/index.js from /home/runner/bard/index.js not supported.
Instead change the require of /home/runner/bard/node_modules/googlebard/dist/index.js in /home/runner/bard/index.js to a dynamic import() which is available in all CommonJS modules.
at Object. (/home/runner/bard/index.js:1:14) {
code: 'ERR_REQUIRE_ESM'
}

Cookie Validity

For How much time does the cookie Valid ?
Am i required to change the cookie every x hours or days ?

Google Bard's Reverse Engineering Ineffectiveness after Update

Hello there! If you're looking to reverse engineer Google Bard, I've got some news for you. Due to a recent update, Google Bard's behavior has changed, making traditional reverse engineering methods less fruitful. The current version of Google Bard, when prompted, simply responds by echoing back your original input. Consequently, attempting to delve into the inner workings of Google Bard to uncover its underlying mechanisms may yield limited or unsatisfactory results. It's akin to peering into a puzzle box, only to find a reflection of your own query staring back at you. Therefore, the effectiveness of reverse engineering Google Bard has been curtailed with this update.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.