Skip to content
This repository has been archived by the owner on Apr 24, 2024. It is now read-only.

Issue is still there Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'. #99

Closed
ranjan-sumit opened this issue Jul 12, 2023 · 51 comments
Labels
good first issue Good for newcomers

Comments

@ranjan-sumit
Copy link

Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'.****

@dsdanielpark
Copy link
Owner

dsdanielpark commented Jul 12, 2023

Not package-related issue, but possible action on the account due to unauthorized usage (excessive traffic).

I have confirmed that there are no major issues with the current functioning of the package, and it is operating normally.

As mentioned in various issues and the README.md, bardapi was implemented to support developers in mocking and implementing certain testing functionalities before the official package distribution of bard. Please note that the token values used are associated with Google accounts.

This particular issue could be a precautionary measure against unauthorized usage (such as excessive traffic), and if you continue to use it, there is a possibility of encountering issues with your Google account.

Therefore, I strongly advise against using this package to generate excessive traffic and recommend checking the official API documentation instead.

#97 #99

Therefore, various types of errors (Nonetype, SNIM0e value, Response Error) may occur, but these are not package-related issues and could be actions taken by Google regarding the account.

We recommend trying with the cookie value of a different account or checking the functionality in Google Colab or Logout and Re-Login. According to other users, it should return to normal operation after a few hours. Thank you.

@nikk-16
Copy link

nikk-16 commented Jul 12, 2023

There is no issue int this API.
But after excessive usage, the Google knows that cookie is having unauthorized access so the 1PSID is revert in some form.

The reason we get : Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'

How can you get rid of it:
Clear cookies of bard.google.com and again

  • login into the account
  • F12 > Applications > Cookies > bard > __Secure-1PSID
  • Copy cookie and paste into your code.

Re run and you are good to go.

@pixkk
Copy link

pixkk commented Jul 13, 2023

Admin. We need use two cookies - __Secure-1PSID and __Secure-1PSIDTS. Without __Secure-1PSIDTS html page bard.google.com has unauthorized user.

@dsdanielpark
Copy link
Owner

If you need to set multi cookie value. Using Bard Cookies Object.

from bardapi import BardCookies

cookie_dict = {
    "__Secure-1PSID": "xxxxxxxxx",
    "__Secure-1PSIDTS": "xxxxxxxxx",
    # Any cookie values you want to pass session object.
}

bard = BardCookies(cookie_dict=cookie_dict)

print(bard.get_answer("こんにちは"))

@TanukiAI
Copy link

On Windows, importing BardCookies is not possible:

>>> from bardapi import BardCookies
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'BardCookies' from 'bardapi' (C:\Program Files\Python310\lib\site-packages\bardapi\__init__.py)

@dsdanielpark
Copy link
Owner

dsdanielpark commented Jul 14, 2023

Upon rechecking, I confirmed that there were no issues with the implementation of BardCookies.

Additionally, I remembered that it was separated as a standalone entity to avoid any potential issues arising in the Bard class. Therefore, your suggestion was already present in BardCookies, and it was functioning properly on both Windows and Linux.

Check version and you can use BardCookies that exatly same except can pass cookie dictionary as argument.

from bardapi import BardCookies

cookie_dict = {
    "__Secure-1PSID": "xxxxxxxxx",
    "__Secure-1PSIDTS": "xxxxxxxxx",
    "__Secure-1PSIDCC", "xxxxxxx")
}

bard = BardCookies(cookie_dict=cookie_dict)

print(bard.get_answer("こんにちは"))

@TanukiAI
Copy link

But there is a workaround for this looking at the code:

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard

token = "xxxxx"

session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<VALUE>")
session.cookies.set("__Secure-1PSIDCC", "<VALUE>")

bard = Bard(token=token, session=session)

Wouldn't it be possible to pass a dictionary with cookies along?

@TanukiAI
Copy link

Here in Austria, it doesn't work with just the one token.
And even if it's just a minority, I don't think there would be a problem passing an cookie dictionary (basically {"cookie1": "value1", "cookie2": "value"}) along and setting these cookies, too.
Creating the session with the multiple cookies worked.

Unfortunately I can't help currently as I don't have an IDE here and can't install one, I am trying all of this on Windows in Notepad++ plus CLI :/

@parsibox
Copy link

But there is a workaround for this looking at the code:

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard

token = "xxxxx"

session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<VALUE>")
session.cookies.set("__Secure-1PSIDCC", "<VALUE>")

bard = Bard(token=token, session=session)

Wouldn't it be possible to pass a dictionary with cookies along?

this work for me
thanks

@dsdanielpark
Copy link
Owner

dsdanielpark commented Jul 14, 2023

@TanukiAI

On Windows, importing BardCookies is not possible:

>>> from bardapi import BardCookies
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'BardCookies' from 'bardapi' (C:\Program Files\Python310\lib\site-packages\bardapi\__init__.py)

You can still use the Bard class as it is and also have the option to use BardCookies. In fact, both BardCookies and Bard have nearly identical implementations, except that BardCookies can accept additional cookie values as a dictionary.

However, due to my current commitments to another project, I won't be able to address any additional issues that may arise. Therefore, I have decided to maintain this version as it is for now. The development priority has been postponed until a later time when I can address any issues and focus on adding new features.

Anyone is welcome to contribute at any time.
Thank you for your understanding.


How to use BardCookies

BardCookies works fine without any differences on both Windows and Linux. Please reinstall it to ensure you have the latest version.

  1. Reinstall Lastest Version of Bard-API
pip install bardapi>=0.1.24
  1. And check version
import bardapi
bardapi.__version__
>>> '0.1.24'
  1. Using BardCookies
from bardapi import BardCookies

cookie_dict = {
    "__Secure-1PSID": "xxxxxxxxx",
    "__Secure-1PSIDTS": "xxxxxxxxx",
    "__Secure-1PSIDCC", "xxxxxxx")
}

bard = BardCookies(cookie_dict=cookie_dict)

print(bard.get_answer("こんにちは"))

For more feature of Bard-API package, please check this document.

@noseon
Copy link

noseon commented Jul 14, 2023

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard
import json
import os

def load_cookie(element_name):
    with open(os.getcwd() + "/" + "bard.json", "r", encoding="utf-8") as file:
        data = json.load(file)
        if isinstance(data, list):
            for item in data:
                if item.get("name") == element_name:
                    return item.get("value")
        return None

_1PSID = load_cookie("__Secure-1PSID")
_1PSIDTS = load_cookie("__Secure-1PSIDTS")
_1PSIDCC = load_cookie("__Secure-1PSIDCC")
session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", _1PSID)
session.cookies.set("__Secure-1PSIDTS", _1PSIDTS)
session.cookies.set("__Secure-1PSIDCC", _1PSIDCC)

bard = Bard(token=_1PSID, session=session)
print(bard.get_answer("gnomes")['content'])

this working if put in the heart of the api would be better. just passing the json location to get the data

@nerblock
Copy link

Same problem when trying to access Bard from Hungary. __Secure-1PSIDTS needs to be included in the request, and it needs to be rotated every ~20minutes. In the chromium source it is called a bound session cookie:

https://github.com/nwjs/chromium.src/blob/21945e5c163533b01a44214b663a9bf615c31ab5/chrome/browser/signin/bound_session_credentials/bound_session_cookie_refresh_service_impl.cc#L248

@noseon
Copy link

noseon commented Jul 14, 2023

so in this case it would be reloading each question now the section just use __Secure-1PSID?

@TanukiAI
Copy link

Yes, cookies need to be rotated.
An request is sent to https://accounts.google.com/RotateCookies to renew the token.

@nerblock
Copy link

Ok, so the million dollar question is: can we do this without a browser? Because having to replace this cookie manually every 10-20 minutes is bad news for my use case.

@dsdanielpark
Copy link
Owner

dsdanielpark commented Jul 15, 2023

Ok, so the million dollar question is: can we do this without a browser? Because having to replace this cookie manually every 10-20 minutes is bad news for my use case.



While support for this issue is available from version 0.1.26 onwards, it may still be challenging to find a definitive solution.
https://github.com/dsdanielpark/Bard-API#auto-cookie-bard

Auto Cookie Bard

Using browser_cookie3 we extract the `__Secure-1PSID`` cookie from all browsers, and then we can use the API without passing the token. However, there are still incomplete dependency packages and various variables, so please seek assistance in the following GitHub Issues or adjust your browser's version.

from bardapi import Bard

bard = Bard(token_from_browser=True)
res = bard.get_answer("Do you like cookies?")
print(res)

@rajserc
Copy link

rajserc commented Jul 15, 2023

Going to Incognito and collecting the cookie (from the new signin inside incognito) seems to help.

@znishan
Copy link

znishan commented Jul 15, 2023

I agree with @rajserc. The issue seems to be related to being signed to multiple Google accounts in the same browser session.
Opening an Incognito window, and logging into Bard to capture __Secure-1PSID worked for me.

I suppose it's worth a try to log out of all but one account before capturing the Bard token.

@noseon
Copy link

noseon commented Jul 16, 2023

browser_cookie3 using the firefox version it seems that you have to get the sessionstore.js file if that's the case you could make the bard api read this file and that's it it will work continuously and lastingly

@doffn
Copy link

doffn commented Jul 16, 2023

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard
import json
import os

def load_cookie(element_name):
    with open(os.getcwd() + "/" + "bard.json", "r", encoding="utf-8") as file:
        data = json.load(file)
        if isinstance(data, list):
            for item in data:
                if item.get("name") == element_name:
                    return item.get("value")
        return None

_1PSID = load_cookie("__Secure-1PSID")
_1PSIDTS = load_cookie("__Secure-1PSIDTS")
_1PSIDCC = load_cookie("__Secure-1PSIDCC")
session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", _1PSID)
session.cookies.set("__Secure-1PSIDTS", _1PSIDTS)
session.cookies.set("__Secure-1PSIDCC", _1PSIDCC)

bard = Bard(token=_1PSID, session=session)
print(bard.get_answer("gnomes")['content'])

this working if put in the heart of the api would be better. just passing the json location to get the data

it worked for me with out using json

@dsdanielpark dsdanielpark changed the title issue is still there Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'. Issue is still there Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'. Jul 17, 2023
@chandrakalagowda
Copy link

chandrakalagowda commented Jul 17, 2023

There is no issue int this API. But after excessive usage, the Google knows that cookie is having unauthorized access so the 1PSID is revert in some form.

The reason we get : Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'

How can you get rid of it: Clear cookies of bard.google.com and again

  • login into the account
  • F12 > Applications > Cookies > bard > __Secure-1PSID
  • Copy cookie and paste into your code.

Re run and you are good to go.

This worked for me. Thank you.

I am pasting the code for beginners like me who might find it helpful

image

@Stainless5792
Copy link

But there is a workaround for this looking at the code:

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard

token = "xxxxx"

session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<VALUE>")
session.cookies.set("__Secure-1PSIDCC", "<VALUE>")

bard = Bard(token=token, session=session)

Wouldn't it be possible to pass a dictionary with cookies along?

works for me!

@ChrysthianChrisley
Copy link

ChrysthianChrisley commented Aug 14, 2023

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard

token = "xxxxx"

session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<VALUE>")
session.cookies.set("__Secure-1PSIDCC", "<VALUE>")


bard = Bard(token=token, session=session)

Works fine!

@mohan-chinnappan-n
Copy link

Here is chrome extension to get Cookies :
https://chrome.google.com/webstore/detail/cookie-viewer/dedhcncdjkmjpebfohadfeeaopiponca

@zoftdev
Copy link

zoftdev commented Aug 20, 2023

On Windows, importing BardCookies is not possible:

>>> from bardapi import BardCookies
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'BardCookies' from 'bardapi' (C:\Program Files\Python310\lib\site-packages\bardapi\__init__.py)

please use latest version

@naveedazam27
Copy link

Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'.****

clear browser cookies and then try with new cookies data it worked for me :D

@voaneves
Copy link

There is no issue int this API. But after excessive usage, the Google knows that cookie is having unauthorized access so the 1PSID is revert in some form.

The reason we get : Exception: SNlM0e value not found. Double-check __Secure-1PSID value or pass it as token='xxxxx'

How can you get rid of it: Clear cookies of bard.google.com and again

  • login into the account
  • F12 > Applications > Cookies > bard > __Secure-1PSID
  • Copy cookie and paste into your code.

Re run and you are good to go.

It's my first time using it, but your solution actually fixed it for me.

Thanks!

@Johan0401
Copy link

Hello all,
Hope you do well.
I have tried to make an AI chatbot that can talk to me instead of shooting out words. But it gives me all kinds of errors. I no nothing about coding i Just started out.
So here is my code i would appreciate it if someone can tell me what i did wrong.
`!pip install bardapi
from bardapi import Bard
import os
import time
os.environ['_BARD_API_TOKEN'] = "Insert.API here"

Set your input text

input_text = "Why is the sky blue?"

input_text = "What is the current status of Ashes Series 2023"
print(Bard().get_answer(input_text)['content'])`
It gives me the following error.
Exception Traceback (most recent call last) " style="color: var(--colab-anchor-color);"> in <cell line: 5>() 3 input_text = "Why is the sky blue?" 4 # input_text = "What is the current status of Ashes Series 2023" ----> 5 print(Bard().get_answer(input_text)['content'])

1 frames

/usr/local/lib/python3.10/dist-packages/bardapi/core.py in _get_snim0e(self) 114 """ 115 if not self.token or self.token[-1] != ".": --> 116 raise Exception( 117 "__Secure-1PSID value must end with a single dot. Enter correct __Secure-1PSID value." 118 ) Exception: __Secure-1PSID value must end with a single dot. Enter correct __Secure-1PSID value.
The API has a dot, so i don't know why it is not working 😕 would appreciate the help

@dsdanielpark
Copy link
Owner

dsdanielpark commented Aug 28, 2023 via email

@Johan0401
Copy link

I know I gave me the error message I have said above. It says something about the API can't be Authorised.

@Kienvu175
Copy link

I just simply clear cookies, refresh bard,google.com then re-copied the 1PSID then it worked.
Hope this help !

@Ayad-Mihidabi-Khan-Jitu
Copy link

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard

token = "xxxxx"

session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<VALUE>")
session.cookies.set("__Secure-1PSIDCC", "<VALUE>")


bard = Bard(token=token, session=session)

Works fine!

THANKS WORKED

@dsdanielpark dsdanielpark added the good first issue Good for newcomers label Sep 3, 2023
@vincecalpari
Copy link

Same problem when trying to access Bard from Hungary. __Secure-1PSIDTS needs to be included in the request, and it needs to be rotated every ~20minutes. In the chromium source it is called a bound session cookie:

https://github.com/nwjs/chromium.src/blob/21945e5c163533b01a44214b663a9bf615c31ab5/chrome/browser/signin/bound_session_credentials/bound_session_cookie_refresh_service_impl.cc#L248

Tested and verified above, same issue in Sri Lanka, the __Secure-1PSIDTS rotates every ~20mins. Secure-1PSID & Secure-1PSIDCC can be kept the same, but we have to manually retrieve the Secure-1PSIDTS key every 20 mins.
Any work around for this concern? Using bard api as a learning task, help would be appreciated!

session.cookies.set("__Secure-1PSID", "same-xxx")
session.cookies.set( "__Secure-1PSIDCC", "same-xxx")
session.cookies.set("__Secure-1PSIDTS", "change-every-20-mins")

@lionkingsiro
Copy link

how to refresh and get new __Secure-1PSIDTS or __Secure-3PSIDTS by java code? i block all xhr request with out https://mobilesdk-pa.clients6.google.com/v1/projects/xxxx:queryBilledUsage, and browser try create new token and get succes. I think __Secure-3PSIDTS generated by javascript.

@phamxtien
Copy link

phamxtien commented Sep 11, 2023

I fix it by update cookie after every request
cookies = []
for k, v in bard.session.cookies.get_dict().items():
cookies.append({'name': k, 'value': v})

@digitalboy
Copy link

But there is a workaround for this looking at the code:

import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard

token = "xxxxx"

session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<VALUE>")
session.cookies.set("__Secure-1PSIDCC", "<VALUE>")

bard = Bard(token=token, session=session)

Wouldn't it be possible to pass a dictionary with cookies along?

Thank you! It is working.........

@shaggy2626
Copy link

shaggy2626 commented Oct 4, 2023

I've been experimenting with the Bard API for some time now, and I seem to be encountering a couple of problems that I hope someone can help me clarify.

The main objective is to upload images via the Bard API. While I have managed to get this working, I've noticed that the tokens refresh frequently. When processing a batch of 50-100 images, the tokens tend to change after the first 5 responses.

I've been following the discussion in this thread and tried implementing browser_cookie3 as suggested in the Bard API's home page. However, while my script runs fine, it's not practical to update the tokens manually each time. I was wondering if anyone has been able to successfully use browser_cookie3 to pull all three parameters from the Bard cookies: __Secure-1PSIDTS, __Secure-1PSIDCC, __Secure-1PSID.

While I have access to Visual Question Answering (VQA), I find the Bard UI more user-friendly. The prompt length restriction (80 tokens max) in VQA also makes Bard a more preferable option.

If anyone has managed to resolve the token refresh issue without having to manually update the tokens each time, I would greatly appreciate your insights.

Here's the current script that I'm using:

import requests
from bardapi import Bard, SESSION_HEADERS
from PIL import Image
import pandas as pd
import io

def main():
    session = requests.Session()
    token = "insert here"

    # Set your cookies
    session.cookies.set("__Secure-1PSID", token)
    session.cookies.set("__Secure-1PSIDCC", "insert here")
    session.cookies.set("__Secure-1PSIDTS", "insert here")

    # Set the session headers
    session.headers = SESSION_HEADERS

    # Send an API request and get a response
    bard = Bard(token=token, session=session)

    # Load the text file and read the URLs
    with open('C:\\Users\\Downloads\\SectionalShape.txt', 'r') as f:
        urls = f.readlines()

    # Iterate over the URLs
    for url in urls:
        url = url.strip()  # Remove leading/trailing whitespace (including newline)

        # Get the image from the URL
        response = requests.get(url)

        # Debug: Print the status code and content type of the response
        print(f"Status code: {response.status_code}")
        print(f"Content-Type: {response.headers['content-type']}")

        try:
            # Open the image and convert it to bytes
            image = Image.open(io.BytesIO(response.content))
            byte_arr = io.BytesIO()
            image.save(byte_arr, format='JPEG')
            image_data = byte_arr.getvalue()
        except UnidentifiedImageError:
            print(f"Unable to open image from URL: {url}")
            continue

        # Ask the Bard API about the image
        bard_answer = bard.ask_about_image('What is in the image?', image_data)

        # Write the URL and response to the text file
        with open('C:\\Users\\Downloads\\SectionalShape.txt', 'a') as f:
            f.write(f"{url},{bard_answer['content']}\n")

if __name__ == "__main__":
    main()

Thank you in advance!


@nguyenduclong1147
Copy link

nguyenduclong1147 commented Oct 4, 2023

I created function get cookies from chorme. You can fix the error PermissionError: [Errno 13] Permission denied at borisbabic/browser_cookie3#180 (comment)

  def _extract_bard_cookie() -> dict:
        cookie_dict = {}
    
        cj = browser_cookie3.chrome(cookie_file=r'C:\Users\<your user>\AppData\Local\Google\Chrome\User Data\Default\Network\Cookies',domain_name=".google.com")

        for cookie in cj:
            if cookie.name == "__Secure-1PSID" and cookie.value.endswith("."):
                cookie_dict["__Secure-1PSID"] = cookie.value
            if cookie.name == "__Secure-1PSIDTS":
                cookie_dict["__Secure-1PSIDTS"] = cookie.value
            if cookie.name == "__Secure-1PSIDCC":
                cookie_dict["__Secure-1PSIDCC"] = cookie.value

        logging.info(cookie_dict)
        return cookie_dict

@shaggy2626
Copy link

I created function get cookies from chorme. You can fix the error PermissionError: [Errno 13] Permission denied at borisbabic/browser_cookie3#180 (comment)

  def _extract_bard_cookie() -> dict:
        cookie_dict = {}
    
        cj = browser_cookie3.chrome(cookie_file=r'C:\Users\<your user>\AppData\Local\Google\Chrome\User Data\Default\Network\Cookies',domain_name=".google.com")

        for cookie in cj:
            if cookie.name == "__Secure-1PSID" and cookie.value.endswith("."):
                cookie_dict["__Secure-1PSID"] = cookie.value
            if cookie.name == "__Secure-1PSIDTS":
                cookie_dict["__Secure-1PSIDTS"] = cookie.value
            if cookie.name == "__Secure-1PSIDCC":
                cookie_dict["__Secure-1PSIDCC"] = cookie.value

        logging.info(cookie_dict)
        return cookie_dict

I tried that but im getting permission denied is this still working for you?
image

Traceback (most recent call last):
  File "C:\barderlatestgreat\bard_test.py", line 113, in <module>
    main()
  File "C:\barderlatestgreat\bard_test.py", line 26, in main
    cookie_dict = _extract_bard_cookie()
                  ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\barderlatestgreat\bard_test.py", line 12, in _extract_bard_cookie
    cj = browser_cookie3.chrome(cookie_file='C:\\Users\\abc40\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Network\\Cookies', domain_name=".google.com")
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abc40\AppData\Local\Programs\Python\Python311\Lib\site-packages\browser_cookie3\__init__.py", line 1160, in chrome
    return Chrome(cookie_file, domain_name, key_file).load()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abc40\AppData\Local\Programs\Python\Python311\Lib\site-packages\browser_cookie3\__init__.py", line 489, in load
    with _DatabaseConnetion(self.cookie_file) as con:
  File "C:\Users\abc40\AppData\Local\Programs\Python\Python311\Lib\site-packages\browser_cookie3\__init__.py", line 349, in __enter__
    return self.get_connection()
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abc40\AppData\Local\Programs\Python\Python311\Lib\site-packages\browser_cookie3\__init__.py", line 383, in get_connection
    con = method()
          ^^^^^^^^
  File "C:\Users\abc40\AppData\Local\Programs\Python\Python311\Lib\site-packages\browser_cookie3\__init__.py", line 374, in __get_connection_legacy
    shutil.copyfile(self.__database_file, self.__temp_cookie_file)
  File "C:\Users\abc40\AppData\Local\Programs\Python\Python311\Lib\shutil.py", line 256, in copyfile
    with open(src, 'rb') as fsrc:
         ^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\abc40\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Network\\Cookies'

Process finished with exit code 1

@nguyenduclong1147
Copy link

Try running the terminal with admin and remember to restart Chrome

@shaggy2626
Copy link

shaggy2626 commented Oct 4, 2023

After restarting Chrome, the implementation is functioning as expected. Currently, requests to Google API are made sequentially, awaiting each response before proceeding to the next. Given this setup, I'm interested to know if you has encountered rate limiting or blocks from Google. The plan is to make 100-200 sequential calls.

There's a segment of code dedicated to updating cookies after each request:

# Update cookies after every request
cookies = []
for k, v in bard.session.cookies.get_dict().items():
    cookies.append({'name': k, 'value': v})

Is this necessary.

Here is the complete updated code:

Click to expand! ````python import requests from bardapi import Bard, SESSION_HEADERS from PIL import Image from PIL import UnidentifiedImageError import pandas as pd import io import json import browser_cookie3

def _extract_bard_cookie() -> dict:
cookie_dict = {}
cj = browser_cookie3.chrome(cookie_file='C:\Users\\AppData\Local\Google\Chrome\User Data\Default\Network\Cookies', domain_name=".google.com")
for cookie in cj:
if cookie.name == "__Secure-1PSID" and cookie.value.endswith("."):
cookie_dict["__Secure-1PSID"] = cookie.value
if cookie.name == "__Secure-1PSIDTS":
cookie_dict["__Secure-1PSIDTS"] = cookie.value
if cookie.name == "__Secure-1PSIDCC":
cookie_dict["__Secure-1PSIDCC"] = cookie.value
return cookie_dict

def main():
session = requests.Session()

# Get token and cookies from Chrome
cookie_dict = _extract_bard_cookie()
token = cookie_dict["__Secure-1PSID"]

# Set your cookies
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDCC", cookie_dict["__Secure-1PSIDCC"])
session.cookies.set("__Secure-1PSIDTS", cookie_dict["__Secure-1PSIDTS"])

# Set the session headers
session.headers = SESSION_HEADERS

# Send an API request and get a response
bard = Bard(token=token, session=session)

# Continue with the rest of your code...


# Load the text file and read the URLs
with open('C:\\Users\\\\Downloads\\Shape.txt', 'r') as f:
    urls = f.readlines()

# Get the total number of URLs
total_urls = len(urls)

# List to store the output data
output_data = []

# Set the batch size
batch_size = 5

# Iterate over the URLs
for i, url in enumerate(urls):
    url = url.strip()  # Remove leading/trailing whitespace (including newline)

    # Print the current row number
    print(f"Processing row {i + 1} / {total_urls}")

    try:
        # Get the image from the URL
        response = requests.get(url)
        response.raise_for_status()  # This line will raise an exception if the request failed

        # Debug: Print the status code and content type of the response
        print(f"Status code: {response.status_code}")
        print(f"Content-Type: {response.headers['content-type']}")

        try:
            # Open the image and convert it to bytes
            image = Image.open(io.BytesIO(response.content))
            byte_arr = io.BytesIO()
            image.save(byte_arr, format='JPEG')
            image_data = byte_arr.getvalue()
        except UnidentifiedImageError:
            print(f"Unable to open image from URL: {url}")
            continue

        # Ask the Bard API about the image
        bard_answer = bard.ask_about_image('What is in the image?', image_data)

        # Add the URL and response to the output data
        output_data.append({
            "url": url,
            "response": bard_answer['content']
        })

    except requests.exceptions.RequestException as e:
        print(f"Error when trying to access {url}: {e}")
        output_data.append({
            "url": url,
            "response": str(e)
        })

    # Write the output data to a JSON file every batch_size URLs
    if (i + 1) % batch_size == 0:
        with open('C:\\Users\\\\Downloads\\ectionalshape.json', 'w') as f:
            json.dump(output_data, f, indent=4)

    # Update cookies after every request
    cookies = []
    for k, v in bard.session.cookies.get_dict().items():
        cookies.append({'name': k, 'value': v})

# Write any remaining output data after processing all URLs
with open('C:\\Users\\\\Downloads\\onalshape.json', 'w') as f:
    json.dump(output_data, f, indent=4)

if name == "main":
main()

@nguyenduclong1147
Copy link

I once ran 20 requests at once, nothing happened. You can ask bard, it seems unlimited requests. bard is still in beta. Still, you should be cautious

@shaggy2626
Copy link

I once ran 20 requests at once, nothing happened. You can ask bard, it seems unlimited requests. bard is still in beta. Still, you should be cautious

I was running through intelli J one request after the other and at around 80-90 i got blocked, now even when i try directly through the Bard web UI directly it doesnt go through. i tried another google account and it works but when im using the script im getting stopped.

image

@nguyenduclong1147
Copy link

nguyenduclong1147 commented Oct 5, 2023

Probably because of my area, you can ask bard or find bard policy

@umaisyaqoob
Copy link

SNlM0e value not found in response. Check __Secure-1PSID value.

This error resolve with clear cookies and repost in own code So your code is runing smooth

@hharera
Copy link

hharera commented Feb 9, 2024

My Solution to this issue

import os
import requests
from bardapi import Bard
from dotenv import load_dotenv
from bardapi import BardCookies


load_dotenv('../.env')
token = os.getenv('bard_token')
token_ts = os.getenv('bard_token_ts')

session = requests.Session()
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", token_ts)
session.headers = {
  "Host": "gemini.google.com",
  "X-Same-Domain": "1",
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
  "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  "Origin": "https://gemini.google.com",
  "Referer": "https://gemini.google.com/app",
}
bard = Bard(token=token, session=session)
answer = bard.get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']
print(answer)

@dsdanielpark
Copy link
Owner

[NOTICE] Please, go to Gemini-API https://github.com/dsdanielpark/Gemini-API

Gemini Icon Google - Gemini API

A unofficial Python wrapper, python-gemini-api, operates through reverse-engineering, utilizing cookie values to interact with Google Gemini for users struggling with frequent authentication problems or unable to authenticate via Google Authentication.

Collaborated competently with Antonio Cheong.

What is Gemini?

[Paper] [Official Website] [Official API] [API Documents]

Gemini is a family of generative AI models developed by Google DeepMind that is designed for multimodal use cases. The Gemini API gives you access to the Gemini Pro and Gemini Pro Vision models. In February 2024, Google's Bard service was changed to Gemini.


Installation

pip install python-gemini-api
pip install git+https://github.com/dsdanielpark/Gemini-API.git

For the updated version, use as follows:

pip install -q -U python-gemini-api

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests