diff --git "a/app.py" "b/app.py"
--- "a/app.py"
+++ "b/app.py"
@@ -1,15 +1,10 @@
-'''f0'''
-
-
-'''IMPORTS'''
import os
import time
import json
-import base64
-import requests
import datetime
-from copy import deepcopy
from pathlib import Path
+import random
+import emoji
import pandas as pd
import secrets
import string
@@ -24,30 +19,26 @@ from starlette.responses import RedirectResponse
from starlette import status
from oauth2client import client
from authlib.oidc.core.claims import UserInfo
-# from apiclient import discovery
from urllib.parse import urlparse, urlunparse
-from components.emails.emails import (
- SCOPES, authenticate_gmail,
- get_labels, LABEL_COLS, LABEL_DB,
- get_emails, EMAIL_COLS, EMAIL_DB,
+import gradio as gr
+import uvicorn
+from components.gradio.api import (
+ googleAuth_api, checkDB_api, checkUser_api,
+ syncNotion_api, updateDB_api, notionAuth_api,
+ notionCreatePage_api, notionUpdatePage_api,
+ invokeLLM_api, getLabels_api,
+ addSession_api, deleteUser_api, insertDB_api)
+from components.llm_response import preprocess_llm_response, NOTION_VALID_EMOJIS
+from data.sample import (
+ LABEL_COLS, LABEL_DB,
+ EMAIL_COLS, EMAIL_DB,
EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_DB, SENDER_SUMMARY_DB,
UNSUB_COLS, UNSUB_DB,
PROCESSING_ERRORS_COLS, PROCESSING_ERRORS_DB,
- ANALYSIS_TYPES, FILE_PATHS,
- pretty_print_blueprint)
-from components.supabase.db import (
- check_user, create_google_user, create_pwd_user,
- check_data, insert_data, update_data, update_row,
- revoke_google_token)
-from components.notion.auth import fetch_user_pages, parse_user_pages
-from components.notion.architect import to_notion, to_notion_new, process_blueprint
-from components.notion.blocks import create_page
-from components.storage.tables import save_data_to_csv, save_data_to_excel
-from components.gen_ai.notion_gen import generate_blueprint, invoke_llm
-
-import gradio as gr
-import uvicorn
+ ANALYSIS_TYPES, FILE_PATHS)
+from data.tables import save_data_to_csv, save_data_to_excel
+from components.fetch_emails import get_emails
APPLICATION_NAME = "f0"
@@ -59,22 +50,17 @@ GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')
SESSION_MIDDLEWARE_SECRET_KEY = os.getenv('SESSION_MIDDLEWARE_SECRET_KEY')
NOTION_AUTHORIZATION_ENDPOINT = os.getenv('NOTION_AUTHORIZATION_URL')
-NOTION_CLIENT_ID = os.getenv('NOTION_OAUTH_CLIENT_ID')
-NOTION_CLIENT_SECRET = os.getenv('NOTION_OAUTH_CLIENT_KEY')
NOTION_REDIRECT_URI = os.getenv('NOTION_REDIRECT_URI')
-NOTION_ACCESS_TOKEN_URL = 'https://api.notion.com/v1/oauth/token'
PUBLIC_NOTION_KEY = os.getenv('PUBLIC_DIR_NOTION_KEY')
-PUBLIC_NOTION_PAGE_ID = os.getenv("PUBLIC_DIR_NOTION_PAGE_ID")
-OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
-MODEL_NAME = os.getenv('MODEL_NAME')
-UNSPLASH_ACCESS_KEY = os.getenv('UNSPLASH_ACCESS_KEY')
+# MODEL_NAME = os.getenv('MODEL_NAME')
NOTIONGEN_PUBLIC_PAGE_ID = os.getenv('NOTIONGEN_PUBLIC_DIR_PAGE_ID')
-ADMIN_NOTION_KEY = os.getenv('NOTION_KEY')
-ADMIN_NOTION_PAGE_ID = os.getenv('NOTION_PAGE_ID')
-HUGGINGFACEHUB_API_TOKEN = os.getenv('HUGGINGFACEHUB_API_TOKEN')
-ADMIN_USER = os.getenv('ADMIN_USERNAME')
-ADMIN_PWD = os.getenv('ADMIN_PASSWORD')
+SAMPLE_NOTIONGEN_PAGE_ID = os.getenv('SAMPLE_NOTIONGEN_PAGE_ID')
+SAMPLE_NOTIONGEN_PAGE_NAME = os.getenv('SAMPLE_NOTIONGEN_PAGE_NAME')
+PUBLIC_NOTION_PAGE_ID = os.getenv("PUBLIC_DIR_NOTION_PAGE_ID")
+SAMPLE_EMAIL0_PAGE_ID = os.getenv('SAMPLE_EMAIL0_PAGE_ID')
+SAMPLE_EMAIL0_PAGE_NAME = os.getenv('SAMPLE_EMAIL0_PAGE_NAME')
+SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' # we are using modify and not readonly, as we will be marking the messages Read
SESSION_DATA={}
SESSION_CHECK_REDIRECTION_URL = "/"
SIGNIN_URL = "/signin"
@@ -88,9 +74,6 @@ LOGOUT_URL = "/logout"
DELETE_ACCOUNT_URL = "/delete_account"
DEMO_USERNAME = 'f0_demo_user'
DEMO_USERPWD = 'f0_demo_pwd'
-SAMPLE_NOTION_TOKEN = 'secret_ab9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
-SAMPLE_NOTION_PAGE_ID = f'EXAMPLE PAGEID: {PUBLIC_NOTION_PAGE_ID}'
-API_URL = "/apis"
'''CODE'''
@@ -102,25 +85,50 @@ oauth.register(
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'},
)
-# TO TEST GOOGLE OAUTH WITHOUT RUNNING THE APP
-# https://accounts.google.com/o/oauth2/auth?client_id={client_id}&response_type=token&redirect_uri={redirect_uri}&scope={scope}
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=SESSION_MIDDLEWARE_SECRET_KEY)
+
+'''APP CODE'''
+# GENERIC FUNCTIONS
def get_user(request: Request): # Dependency to get the current user name
user = request.session.get('user')
- if user:
+ if user and isinstance(user, dict) and user.get('name',None):
+ return user['name']
+ return None
+
+def app_auth(request: Request): # Dependency to get the current user name
+ user = request.session.get('user')
+ # if user is None:
+ # raise HTTPException(status_code=401, detail="Test Unauthorized")
+ if user and isinstance(user, dict) and user.get('name',None):
return user['name']
return None
-def get_user_info(user, session_data): # Dependency to get the current user info
+# from starlette.exceptions import HTTPException as StarletteHTTPException
+# @app.exception_handler(HTTPException)
+# def http_exception_handler(request: Request, exc: HTTPException):
+# print("Printing the error.....")
+# print(request.session.get('user'))
+# print(exc.status_code)
+# print("Proceeding with the next action.....")
+# if exc.status_code == 401:
+# # Redirect to the login page if the user is unauthorized
+# return RedirectResponse(url="/signin")
+# # Return the default exception handler for other HTTP errors
+# return JSONResponse(
+# status_code=exc.status_code,
+# content={"detail": exc.detail}
+# )
+
+def get_user_info(user): # Dependency to get the current user info
# user = request.session.get('user',{})
_user_type = "google"
_id_type = 'email'
_curr_user_id = user.get(_id_type,'')
if not _curr_user_id:
- _session_user = session_data.get('user',{})
+ _session_user = SESSION_DATA.get('user',{})
_user_type = "pwd"
_id_type = 'email'
_curr_user_id = _session_user.get(_id_type,'')
@@ -131,49 +139,64 @@ def get_user_info(user, session_data): # Dependency to get the current user info
return _user_type, _id_type, _curr_user_id
return None, None, None
-def get_session(_curr_user_id, _id_type):
- data, count = check_data(_curr_user_id, column="id", table="users", row_id_type=_id_type) # Fetch users id
- _users_id = data[0].get('id',None)
- data, count = check_data(_users_id, "*", "sessions", "users_id")
- sorted_data = None
- if data:
- sorted_data = sorted(data, key=lambda x: x['created_at'], reverse=True)
- return sorted_data, _users_id
-
-def add_session(_curr_user_id:str, _id_type:str, session:dict):
- session_data, _users_id = get_session(_curr_user_id, _id_type)
- if not session_data:
- print("1st session of a new user")
- data, count = insert_data({"users_id": _users_id, "session": session}, "sessions")
- return data
- elif session_data[0]['session'] != session:
- print("New session of an existing user")
- data, count = insert_data({"users_id": session_data[0]['users_id'], "session": session}, "sessions")
- return data
+def greet(request: gr.Request):
+ return f"""### 👋, {SESSION_DATA.get('user',{}).get('username',request.username)}."""
+
+def user_details(request: gr.Request):
+ return f"""### My Username: {SESSION_DATA.get('user',{}).get('username',None)}""", f"""### My Name: {SESSION_DATA.get('user',{}).get('name',request.username)}""", f"""### My Email: {SESSION_DATA.get('user',{}).get('email',None)}"""
+
+def get_usage_limits(session_data):
+ curr_user = session_data.get('user','')
+ _usage_limits = None
+ _user_type = None
+ _curr_user_email = None
+ if curr_user:
+ _curr_user_email = curr_user.get('email','')
+ _user_type = 'email'
+ if not _curr_user_email:
+ _curr_user_email = curr_user.get('username','')
+ _user_type = 'username'
+ response = checkDB_api(row_id_value=_curr_user_email, column="usage_limits, id", table="users", row_id_type=_user_type)
+ if response:
+ _usage_limits = response
+ if _usage_limits:
+ return _usage_limits[0], _user_type, _curr_user_email
else:
- print("Same Session. Skipping...")
- return None
+ return {}, _user_type, _curr_user_email
+def get_connected_notion_info(refresh=False,max_depth=2):
+ curr_user = SESSION_DATA.get('user','')
+ token = None
+ page_id = None
+ page_types = None
+ if curr_user and (isinstance(curr_user,UserInfo) or isinstance(curr_user,dict)):
+ curr_user_email = curr_user.get('email','')
+ _user_type = 'email'
+ if not curr_user_email:
+ curr_user_email = curr_user.get('username','')
+ _user_type = 'username'
+ if curr_user_email:
+ return syncNotion_api(row_id_value=curr_user_email,row_id_type=_user_type,refresh=refresh,max_depth=max_depth)
+ return token, page_id, page_types
# ROUTER FUNCTIONS
@app.get(SESSION_CHECK_REDIRECTION_URL)
-def app_router(request: Request, user = Depends(get_user)):
+def app_router(user = Depends(get_user)):
if user:
- # user = request.session.get('user',{})
- # session_data = add_session(user, request.cookies)
return RedirectResponse(url=APP_URL)
else:
return RedirectResponse(url=SIGNIN_URL)
@app.route(GOOGLE_SIGNIN_URL)
async def google_login(request: Request):
- print("Initiating Google sign-in flow......")
user = request.session.get('user',{})
- # _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
+ _user_type, _id_type, _curr_user_id = get_user_info(user)
creds = None
if user:
- print(f'User [{user.get("name",None)}, {user.get("email",None)}] session found')
- creds_json, count = check_data(user['email'], column="auth_response", table="users", row_id_type="email")
+ creds_json = None
+ response = checkDB_api(row_id_value=user['email'], column="auth_response", table="users", row_id_type="email")
+ if response:
+ creds_json = response
if creds_json:
print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
@@ -184,7 +207,6 @@ async def google_login(request: Request):
if not creds.invalid:
print("Credentials refreshed successfully.")
creds_json = creds.to_json()
- pretty_print_blueprint(creds_json)
# data = google_auth_db_sync(creds_json, user, scope='google')
# return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
except client.AccessTokenRefreshError:
@@ -196,22 +218,22 @@ async def google_login(request: Request):
print("No credentials found. Initiating Google sign-in flow.")
else:
print("No user session found. Initiating Google sign-in flow.")
-
- # oauth._clients['google'].client_kwargs['scope'] = f'openid email profile'
+
+ # oauth._clients['google'].client_kwargs['scope'] = f'openid email profile'
redirect_uri = request.url_for('google_auth')
redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme=URL_SCHEMA))
- # print(redirect_uri)
return await oauth.google.authorize_redirect(request, redirect_uri, access_type='offline')
@app.route('/google_auth')
async def google_auth(request: Request):
try:
user = request.session.get('user',{})
- # _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
creds = None
if user:
- print(f'User [{user.get("name",None)}, {user.get("email",None)}] session found')
- creds_json, count = check_data(user['email'], column="auth_response", table="users", row_id_type="email")
+ creds_json = None
+ response = checkDB_api(row_id_value=user['email'], column="auth_response", table="users", row_id_type="email")
+ if response:
+ creds_json = response
if creds_json:
print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
@@ -222,7 +244,6 @@ async def google_auth(request: Request):
if not creds.invalid:
print("Credentials refreshed successfully.")
creds_json = creds.to_json()
- pretty_print_blueprint(creds_json)
# data = google_auth_db_sync(creds_json, user, scope='google')
# return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
except client.AccessTokenRefreshError:
@@ -236,171 +257,108 @@ async def google_auth(request: Request):
print("No user session found. Initiating Google sign-in flow.")
access_token = await oauth.google.authorize_access_token(request)
- data = google_auth_db_sync(access_token, user, scope='google', session_data=SESSION_DATA)
+ data = []
+ response = googleAuth_api(access_token, user, 'google', SESSION_DATA)
+ if response:
+ data = response
request.session['user'] = dict(access_token)["userinfo"]
SESSION_DATA['user'] = dict(access_token)["userinfo"]
if data and data[0].get('username',None):
SESSION_DATA['user']['username'] = data[0].get('username')
- user = request.session.get('user',{})
- _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
- session_data = add_session(_curr_user_id, _id_type, request.cookies)
- if session_data:
- SESSION_DATA['user']['session_id'] = session_data[0].get('id')
+ _user_type, _id_type, _curr_user_id = get_user_info(request.session.get('user',{}))
+ session_data = addSession_api(_curr_user_id, _id_type, request.cookies)
+ if session_data and session_data.get('Success') and session_data.get('session_data'):
+ SESSION_DATA['user']['session_id'] = session_data.get('session_data')[0].get('id')
return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
- except Exception as e:
- print(str(e))
+ except OAuthError:
return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
@app.route(GMAIL_SIGNIN_URL)
async def gmail_login(request: Request):
- print("Initiating Gmail sign-in flow......")
user = request.session.get('user',{})
- # _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
+ _user_type, _id_type, _curr_user_id = get_user_info(user)
creds = None
if user:
- print(f'User [{user.get("name",None)}, {user.get("email",None)}] session found')
- creds_json, count = check_data(user['email'], column="gmail_token", table="users", row_id_type="email")
+ creds_json = None
+ response = checkDB_api(row_id_value=user['email'], column="gmail_token", table="users", row_id_type="email")
+ if response:
+ creds_json = response
if creds_json:
print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
- _missing_scopes = []
- for _scope in SCOPES:
- if _scope not in creds_json['scopes']:
- _missing_scopes.append(_scope)
- if len(_missing_scopes) == 0:
- creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
- if creds.invalid:
- print("Credentials are invalid, attempting to refresh.")
- try:
- creds.refresh(Http())
- if not creds.invalid:
- print("Credentials refreshed successfully.")
- creds_json = creds.to_json()
- pretty_print_blueprint(creds_json)
- # data = google_auth_db_sync(creds_json, user, scope='gmail')
- # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
- except client.AccessTokenRefreshError:
- print("Failed to refresh access token.")
- else:
- print("Valid credentials found. Redirecting.")
- return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
+ creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
+ if creds.invalid:
+ print("Credentials are invalid, attempting to refresh.")
+ try:
+ creds.refresh(Http())
+ if not creds.invalid:
+ print("Credentials refreshed successfully.")
+ creds_json = creds.to_json()
+ # data = google_auth_db_sync(creds_json, user, scope='google')
+ # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
+ except client.AccessTokenRefreshError:
+ print("Failed to refresh access token.")
else:
- print(f"Required Scopes {_missing_scopes} are not present. Initiating Gmail sign-in flow.")
+ print("Valid credentials found. Redirecting.")
+ return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
else:
print("No credentials found. Initiating Gmail sign-in flow.")
else:
print("No user session found. Initiating Gmail sign-in flow.")
-
- oauth._clients['google'].client_kwargs['scope'] = f'openid profile email {SCOPES[0]}'
+
+ oauth._clients['google'].client_kwargs['scope'] = f'openid email profile {SCOPES}'
redirect_uri = request.url_for('gmail_auth')
redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme=URL_SCHEMA))
- # print(redirect_uri)
return await oauth.google.authorize_redirect(request, redirect_uri, access_type='offline')
@app.route('/gmail_auth')
async def gmail_auth(request: Request):
try:
user = request.session.get('user',{})
- # _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
creds = None
if user:
- print(f'User [{user.get("name",None)}, {user.get("email",None)}] session found')
- creds_json, count = check_data(user['email'], column="gmail_token", table="users", row_id_type="email")
+ creds_json = None
+ response = checkDB_api(row_id_value=user['email'], column="gmail_token", table="users", row_id_type="email")
+ if response:
+ creds_json = response
if creds_json:
print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
- _missing_scopes = []
- for _scope in SCOPES:
- if _scope not in creds_json['scopes']:
- _missing_scopes.append(_scope)
- if len(_missing_scopes) == 0:
- creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
- if creds.invalid:
- print("Credentials are invalid, attempting to refresh.")
- try:
- creds.refresh(Http())
- if not creds.invalid:
- print("Credentials refreshed successfully.")
- creds_json = creds.to_json()
- pretty_print_blueprint(creds_json)
- # data = google_auth_db_sync(creds_json, user, scope='gmail')
- # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
- except client.AccessTokenRefreshError:
- print("Failed to refresh access token.")
- else:
- print("Valid credentials found. Redirecting.")
- return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
+ creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
+ if creds.invalid:
+ print("Credentials are invalid, attempting to refresh.")
+ try:
+ creds.refresh(Http())
+ if not creds.invalid:
+ print("Credentials refreshed successfully.")
+ creds_json = creds.to_json()
+ # data = google_auth_db_sync(creds_json, user, scope='google')
+ # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
+ except client.AccessTokenRefreshError:
+ print("Failed to refresh access token.")
else:
- print(f"Required Scopes {_missing_scopes} are not present. Initiating Gmail sign-in flow.")
+ print("Valid credentials found. Redirecting.")
+ return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
else:
print("No credentials found. Initiating Gmail sign-in flow.")
else:
print("No user session found. Initiating Gmail sign-in flow.")
access_token = await oauth.google.authorize_access_token(request)
- data = google_auth_db_sync(access_token, user, scope='gmail', session_data=SESSION_DATA)
+ data = []
+ response = googleAuth_api(access_token, user, 'gmail', SESSION_DATA)
+ if response:
+ data = response
request.session['user'] = dict(access_token)["userinfo"]
SESSION_DATA['user'] = dict(access_token)["userinfo"]
if data and data[0].get('username',None):
SESSION_DATA['user']['username'] = data[0].get('username')
- user = request.session.get('user',{})
- _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
- session_data = add_session(_curr_user_id, _id_type, request.cookies)
- if session_data:
- SESSION_DATA['user']['session_id'] = session_data[0].get('id')
+ _user_type, _id_type, _curr_user_id = get_user_info(request.session.get('user',{}))
+ session_data = addSession_api(_curr_user_id, _id_type, request.cookies)
+ if session_data and session_data.get('Success') and session_data.get('session_data'):
+ SESSION_DATA['user']['session_id'] = session_data.get('session_data')[0].get('id')
return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
- except Exception as e:
- print(str(e))
+ except OAuthError:
return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
-def google_auth_db_sync(access_token: dict, user: dict, scope: str, session_data: dict):
- # pretty_print_blueprint(access_token)
- token_data = {
- "access_token": access_token["access_token"],
- "client_id": GOOGLE_CLIENT_ID,
- "client_secret": GOOGLE_CLIENT_SECRET,
- "refresh_token": access_token.get("refresh_token", ""),
- "token_expiry": access_token.get("expires_at", ""),
- "token_uri": "https://oauth2.googleapis.com/token",
- "user_agent": None,
- "revoke_uri": "https://oauth2.googleapis.com/revoke",
- # "id_token": access_token.get("id_token", ""),
- "id_token": None,
- "id_token_jwt": None,
- "token_response": {
- "access_token": access_token["access_token"],
- "expires_in": access_token.get("expires_in", ""),
- "scope": access_token.get("scope", ""),
- "token_type": "Bearer"
- },
- "scopes": access_token.get("scope", "").split(),
- "token_info_uri": "https://oauth2.googleapis.com/tokeninfo",
- "invalid": False,
- "_class": "OAuth2Credentials",
- "_module": "oauth2client.client"}
- if token_data['token_expiry']:
- token_data['token_expiry'] = datetime.datetime.fromtimestamp(token_data['token_expiry']).strftime('%Y-%m-%dT%H:%M:%SZ')
-
- data, count = check_user(access_token.get('userinfo',{}).get('email',None))
- _user_type, _id_type, _curr_user_id = get_user_info(user, session_data)
-
- if not user and not data:
- if _user_type == 'pwd' and _id_type == 'username' and _curr_user_id:
- update_data(_curr_user_id,access_token.get('userinfo',{}).get('email',None), table="users", row_id_type=_id_type, column="email")
- data, count = update_data(_curr_user_id,access_token.get('userinfo',{}).get('name',None), table="users", row_id_type=_id_type, column="name")
- if scope == 'google':
- _col = 'auth_response'
- if scope == 'gmail':
- _col = 'gmail_token'
- data, count = update_data(_curr_user_id,token_data, table="users", row_id_type=_id_type, column=_col)
- else:
- create_google_user(access_token.get('userinfo',{})['email'],access_token.get('userinfo',{})['name'],token_data,exist_check=False,scope=scope)
- else:
- if scope == 'google':
- _col = 'auth_response'
- if scope == 'gmail':
- _col = 'gmail_token'
- data, count = update_data(access_token.get('userinfo').get('email',None),token_data, table="users", row_id_type="email", column=_col)
- return data
-
def generate_random_alphanumeric(length):
alphabet = string.ascii_letters + string.digits # Includes uppercase and lowercase letters and digits
return ''.join(secrets.choice(alphabet) for _ in range(length))
@@ -409,68 +367,31 @@ def pwd_auth(username, password): # Dependency for signin with username/password
if not username or not password or username == '' or password == '':
print('Empty username or password. Try again..')
return False
- _userinfo, _count = check_user(username, type='username')
+ _userinfo = None
+ response = checkUser_api(row_id_value=username, row_id_type="username")
+ if response:
+ _userinfo = response
if _userinfo:
if _userinfo[0].get('password',None) == password:
print("Password match! You're in..")
SESSION_DATA['user'] = {"email": _userinfo[0].get("email",username), "name": _userinfo[0].get("name",username), "username": username}
- _user_type, _id_type, _curr_user_id = get_user_info({}, SESSION_DATA)
- session_data = add_session(_curr_user_id, _id_type, {"session": generate_random_alphanumeric(14)})
- if session_data:
- SESSION_DATA['user']['session_id'] = session_data[0].get('id')
+ _user_type, _id_type, _curr_user_id = get_user_info({})
+ session_data = addSession_api(_curr_user_id, _id_type, {"session": generate_random_alphanumeric(14)})
+ if session_data and session_data.get('Success') and session_data.get('session_data'):
+ SESSION_DATA['user']['session_id'] = session_data.get('session_data')[0].get('id')
return True
else:
print("Password didn't match or not found. Try again or use 'Sign in with Google'..")
- if username == ADMIN_USER and password == ADMIN_PWD:
- print("Admin User! You're in..")
- SESSION_DATA['user'] = {"email": username, "name": username, "username": username}
- return True
else:
print("User not found. Try again..")
return False
-def auth_message(request: gr.Request):
- return f"Welcome, {request.username}"
-
-def notion_auth_db_sync(access_code: str, redirect_uri: str, session_data: dict):
- encoded_credentials = base64.b64encode(f"{NOTION_CLIENT_ID}:{NOTION_CLIENT_SECRET}".encode()).decode() # Encode client_id and client_secret to base64
- headers={
- "Accept": "application/json",
- "Content-Type": "application/json",
- "Authorization": f"Basic {encoded_credentials}"}
- data={
- 'grant_type': 'authorization_code',
- 'code': access_code,
- 'redirect_uri': redirect_uri}
- response = requests.post(NOTION_ACCESS_TOKEN_URL, headers=headers, json=data) # Send a POST request to get the access token
-
- if response.status_code == 200:
- token_data = response.json()
- curr_user = session_data.get('user','')
- if curr_user and (isinstance(curr_user,UserInfo) or isinstance(curr_user,dict)):
- curr_user_email = curr_user.get('email','')
- _row_id = "email"
- if not curr_user_email:
- curr_user_email = curr_user.get('username','')
- _row_id = "username"
- if curr_user_email:
- update_data(curr_user_email, token_data, table="users", row_id_type=_row_id, column="notion_access_token")
- pages_data = fetch_user_pages(token_data['access_token'])
- update_data(curr_user_email, pages_data, table="users", row_id_type=_row_id, column="notion_access_pages")
- else:
- print("🔴 Error! User not found for storing notion access token!")
- else:
- print("🔴 Error! Invalid session for storing notion access token!")
- else:
- print("🔴 Error: Failed to retrieve access token")
-
@app.route(NOTION_AUTH_URL)
async def notion_auth(request: Request):
- print("Initiating Notion Authentication flow......")
try:
access_code = request.query_params.get('code') # GET TEMPORARY ACCESS CODE
if access_code:
- notion_auth_db_sync(access_code,NOTION_REDIRECT_URI,SESSION_DATA)
+ notionAuth_api(access_code,NOTION_REDIRECT_URI,SESSION_DATA)
else:
error = request.query_params.get('error')
print(f"""🔴 NotionAuth Error! {error}""")
@@ -493,51 +414,22 @@ def pwd_logout(request: Request):
for cookie in cookies:
if cookie.startswith('access-token'):
response.delete_cookie(cookie)
- # REFERENCE: https://github.com/gradio-app/gradio/issues/5163
return response
-def delete_user(_curr_user_id:str, _id_type:str, session_data:dict):
- _session_data, _users_id = get_session(_curr_user_id, _id_type)
- if _session_data:
- if session_data.get('user',{}).get('session_id',None) == _session_data[0]['id'] and _curr_user_id != 'f0_demo_user':
- data, count = check_data(_curr_user_id, column="auth_response, gmail_token, notion_access_token", table="users", row_id_type=_id_type)
- if data:
- if data[0].get("auth_response"):
- _access_token = data[0].get("auth_response").get("access_token")
- if _access_token:
- # print("Google Access Token: ", _access_token)
- revoke_google_token(_access_token)
- if data[0].get("gmail_token"):
- _access_token = data[0].get("gmail_token").get("access_token")
- if _access_token:
- # print("Gmail Access Token: ", _access_token)
- revoke_google_token(_access_token)
- # if data[0].get("notion_access_token"):
- # _access_token = data[0].get("notion_access_token").get("access_token")
- # if _access_token:
- # print("Notion Access Token: ", _access_token)
- update_row(_curr_user_id,{"auth_response":None,"gmail_token":None,"notion_access_token":None,"notion_access_pages":None,"email":None,"name":None,"username":None,"password":None},"users",_id_type)
-
@app.route(DELETE_ACCOUNT_URL)
async def delete_account(request: Request):
- # request_details = {
- # "method": request.method,
- # "url": str(request.url),
- # "headers": dict(request.headers),
- # "query_params": dict(request.query_params),
- # "client": request.client.host if request.client else None,
- # "cookies": request.cookies,
- # "base_url": str(request.base_url),
- # "path_params": request.path_params,
- # "session": request.session,
- # }
- # pretty_print_blueprint(request_details)
user = request.session.get('user',{})
- _user_type, _id_type, _curr_user_id = get_user_info(user, SESSION_DATA)
+ _user_type, _id_type, _curr_user_id = get_user_info(user)
if _user_type and _id_type and _curr_user_id:
- update_data(_curr_user_id, {"request_at": datetime.datetime.now().isoformat(),"session": request.cookies,"sessions_id":SESSION_DATA.get('user',{}).get('session_id',None),"userinfo":SESSION_DATA,"client":request.client.host if request.client else None}, "users", _id_type, "delete_request")
- delete_user(_curr_user_id, _id_type, SESSION_DATA)
- return RedirectResponse(url=LOGOUT_URL)
+ updateDB_api(_curr_user_id, {"request_at": datetime.datetime.now().isoformat(),"session": request.cookies,"sessions_id":SESSION_DATA.get('user',{}).get('session_id',None),"userinfo":SESSION_DATA,"client":request.client.host if request.client else None}, "users", _id_type, "delete_request")
+ response = deleteUser_api(_curr_user_id, _id_type, SESSION_DATA)
+ if response and response.get('Success'):
+ return RedirectResponse(url=LOGOUT_URL)
+ else:
+ print(response.get('Error'))
+ return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
+ return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
+
# SIGNIN PAGE (GRADIO)
with gr.Blocks(
@@ -567,60 +459,207 @@ with gr.Blocks(
gr.Markdown("""---""")
gr.Markdown("""#### 💌 Built by [finding0](https://www.linkedin.com/company/finding0)""", elem_classes="center_text")
-
app = gr.mount_gradio_app(app, signin_page, path=SIGNIN_URL)
-'''GENERIC FUNCTIONS'''
-def greet(request: gr.Request):
- return f"""### 👋, {SESSION_DATA.get('user',{}).get('username',request.username)}."""
+# NOTIONGEN APP FUNCTIONS
+ADD_INPUTS = [
+ ["NOTION_KEY",None,"https://www.notion.so/my-integrations"],
+ ["NOTION_PAGE_ID",None,"https://www.notion.so/{ACCOUNT_DOMAIN}/{PAGETITLE}-{PAGEID}?"],
+ ["LLM_API_KEY",None,"https://platform.openai.com/api-keys"],
+ ]
-def user_details(request: gr.Request):
- return f"""### My Username: {SESSION_DATA.get('user',{}).get('username',None)}""", f"""### My Name: {SESSION_DATA.get('user',{}).get('name',request.username)}""", f"""### My Email: {SESSION_DATA.get('user',{}).get('email',None)}"""
+def notiongen_api(
+ description:str, llm:str, model:str,
+ temperature:float = 0.7, top_p:float = 0.2,
+ autosend_to_notion:bool = False, notion_page_id: str = None,
+ notion_page_type:str = None, notion_access_token:str = None,
+ dev_mode:bool = False, key_values:dict = {}
+ ):
+ _query = {"description": description, "llm": llm, "model": model,
+ "temperature": temperature, "top_p": top_p, "dev_mode": dev_mode,
+ "autosend_to_notion": autosend_to_notion, "notion_page_type": notion_page_type}
+ _sample_link = f"""🟡 🏗️ Sample NotionGen Page Link: {SAMPLE_NOTIONGEN_PAGE_NAME} [SAMPLE]"""
+ _action_id = "notiongen_generate"
+ _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
+ _users_id = _usage_limits.get('id',None)
+ _sessions_id = SESSION_DATA.get('user').get('session_id',None)
+ _usage_limits = _usage_limits.get('usage_limits')
+ try:
+ _rem_limits = 1
+ _speed_break_limit_seconds = 300
+ _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
+ gr_tab_id = 1
+ if _usage_limits:
+ if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
+ _page_limits = _usage_limits.get("pages",{}).get(str(gr_tab_id),{})
+ _rem_limits = _page_limits.get("remaining",0)
+ _speed_break_limit_seconds = _page_limits.get("speed_break",300)
+ _last_used_at = _page_limits.get("last_used_at",None)
+ else:
+ _default_limits = _usage_limits.get("default",{})
+ _rem_limits = _default_limits.get("remaining",0)
+ _speed_break_limit_seconds = _default_limits.get("speed_break",300)
+ _last_used_at = _default_limits.get("last_used_at",None)
+ if _last_used_at:
+ _last_used_at = datetime.datetime.strptime(_last_used_at, "%Y-%m-%d %H:%M:%S")
+ else:
+ _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
+ if _rem_limits > 0 and _last_used_at < datetime.datetime.now() - datetime.timedelta(seconds=int(_speed_break_limit_seconds)):
+ yield f"🟡 🏗️ Initializing NotionGen with model {model[:int(len(model)/2)]}...", _sample_link, {"message": f"Initializing NotionGen..."}
+ llm_response = invokeLLM_api(description=description,force_json=True,temperature=temperature,top_p=top_p,llm=llm,model=model,llm_key=None,def_env_var=True,custom_data=None)
+ # yield f"🟡 🏗️ NotionGen template generation is in progress...", """""", {"message": f"NotionGen template generation in-progress..."}
+ _response_json = ""
+ _result = ""
+ _response = ""
+ for _res in preprocess_llm_response(llm_response):
+ time.sleep(0.05)
+ if isinstance(_res, dict):
+ _response_json = _res.get('blueprint', {})
+ _titles = re.findall(r'titled "(.*?)"', _response)
+ _title = _titles[0] if _titles else "Uncategorized"
+ _result = f"🟢 🎉 NotionGen template generation is completed. Now, you can 'Send to Notion' (go to Notion Settings section at the end).\n\n{_response}"
+ if _usage_limits:
+ if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
+ _usage_limits["pages"][str(gr_tab_id)]["remaining"] = _usage_limits["pages"][str(gr_tab_id)]["remaining"] - 1
+ _usage_limits["pages"][str(gr_tab_id)]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ _usage_limits["default"]["remaining"] = _usage_limits["default"]["remaining"] - 1
+ _usage_limits["default"]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ updateDB_api(curr_user_email, update_data=_usage_limits, table="users", row_id_type=_user_type, column="usage_limits")
+ if autosend_to_notion:
+ yield f"🟢 🎉 NotionGen template generation is completed. 🟡 🏗️ Now, sending the template content to Notion...\n\n{_response}", _sample_link, _response_json
+ is_invalid = preprocess_validation(notion_access_token,notion_page_id,notion_page_type)
+ if is_invalid:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}, "notion_response": {"success": False, "data": None, "error": is_invalid}},"title":_title}}, "actions")
+ yield f"🟢 🎉 NotionGen template is successfully generated but can't be sent to Notion due to an error!\n\n{_response}", f"""{is_invalid} or use the public workspace.""", _response_json
+ else:
+ _response_json['properties'] = {
+ 'User': {
+ "rich_text": [{
+ "text": {
+ "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
+ }]}}
+ page_type = _response_json["type"]
+ _new_page_id, _new_page_title, _new_page_link = create_notion_page(_response_json,notion_page_id,notion_page_type,notion_access_token)
+ if _new_page_id:
+ yield f"🟡 🏗️ Notion Page (or Database) is successfully generated & content writing is initiated....\n\n{_response}", f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation: {_new_page_title}""", _response_json
+ for _idx, child in enumerate(_response_json.get("children", [])):
+ block_type = child["type"]
+ yield f"🟡 🏗️ Notion Page (or Database) is successfully generated & content writing is in-progress for a notion block of type '{block_type}'....\n\n{_response}", f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation: {_new_page_title}""", _response_json
+ res = notionUpdatePage_api(parent_id=_new_page_id, block_json=child, notion_access_token=notion_access_token, parent_block_type=page_type)
+ is_success = res.get("Success",False)
+ if not is_success:
+ yield f"🔴 Failed to process block '{block_type}' with error {res.get('Error','')}", f"""🟢 🎉 Check out the NotionGen-generated page: {_new_page_title}""", _response_json
+ if _idx == len(_response_json.get("children", [])) - 1:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}},"title":_title}}, "actions")
+ yield f"🟢 🎉 NotionGen template is successfully sent to Notion!\n\n{_response}", f"""🟢 🎉 Check out the NotionGen-generated page: {_new_page_title}""", _response_json
+ else:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}, "notion_response": {"success": False, "result":_new_page_link, "data": "NotionGen template is successfully generated but template generation without a new Notion page is not supported"}},"title":_title}}, "actions")
+ yield f"🟢 🎉 NotionGen template is successfully generated but template generation without a new Notion page is not supported! Try again to generate a page.\n\n{_response}", _sample_link, _response_json
+ else:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}},"title":_title}}, "actions")
+ yield _result, _sample_link, _response_json
+ else:
+ _response += _res
+ yield _response, _sample_link, {"message": "NotionGen template generation in progress...."}
+ else:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"usage_limit exceeded or reused before the cooling-off period {_speed_break_limit_seconds} (last used at {_last_used_at})"}}}, "actions")
+ yield f"🔴 ⌛ Usage limit exceeded or reuse with a break of {_speed_break_limit_seconds} seconds (last used at {_last_used_at}). Please contact us to generate more content.", _sample_link, {"error": "Usage limit exceeded. Please contact us to generate more content."}
+ except Exception as e:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": str(e)}}}, "actions")
+ yield f"🔴 Error encountered: {str(e)}. Ensure that the 'Inputs' are correctly filled. Run again.", _sample_link, {"error": f"Failed to generate or process NotionGen template due to error {e}"}
-def get_connected_notion_info(refresh=False,max_depth=2):
- curr_user = SESSION_DATA.get('user','')
- token = None
- page_id = None
- page_types = None
- if curr_user and (isinstance(curr_user,UserInfo) or isinstance(curr_user,dict)):
- curr_user_email = curr_user.get('email','')
- _user_type = 'email'
- if not curr_user_email:
- curr_user_email = curr_user.get('username','')
- _user_type = 'username'
- if curr_user_email:
- return parse_user_pages(curr_user_email,user_type=_user_type,refresh=refresh,max_depth=max_depth)
- return token, page_id, page_types
+def preprocess_validation(notion_key,notion_page_id,notion_page_type):
+ # TODO - Put validation of notion page id & notion key formats
+ if not notion_key:
+ update = f"""🔴 Error! Connect Notion"""
+ print(update)
+ return update
+ if not notion_page_id:
+ update = f"""🔴 Error! Select a parent Notion page/database"""
+ print(update)
+ return update
+ if notion_page_type == 'root':
+ update = f"""🔴 Error! Select a non-root page/database"""
+ print(update)
+ return update
+ return None
-def get_usage_limits(session_data):
- curr_user = session_data.get('user','')
- _usage_limits = None
- _user_type = None
- _curr_user_email = None
- if curr_user:
- _curr_user_email = curr_user.get('email','')
- _user_type = 'email'
- if not _curr_user_email:
- _curr_user_email = curr_user.get('username','')
- _user_type = 'username'
- _usage_limits, count = check_data(_curr_user_email, column="usage_limits, id", table="users", row_id_type=_user_type)
- if _usage_limits:
- return _usage_limits[0], _user_type, _curr_user_email
+def create_notion_page(notion_json,parent_page_id,parent_page_type,notion_key):
+ page_type = notion_json["type"]
+ if page_type == "page":
+ page_title = notion_json.get("title", "Untitled Page")
+ print(f"🟡 ⏳ Creating {page_type} '{page_title}' inside parent_type '{parent_page_type}'")
+ emojis = [em for em in emoji.EMOJI_DATA if not any(char in em for char in ["🏻", "🏼", "🏽", "🏾", "🏿", "\u200d"]) and not em.startswith(("🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "🇯", "🇰", "🇱", "🇲", "🇳", "🇴", "🇵", "🇶", "🇷", "🇸", "🇹", "🇺", "🇻", "🇼", "🇽", "🇾", "🇿"))]
+ icon = notion_json.get("icon", random.choice(emojis))
+ is_valid_icon = icon in NOTION_VALID_EMOJIS
+ if not is_valid_icon:
+ icon = random.choice(emojis)
+ properties = notion_json.get("properties", {})
+ new_page = notionCreatePage_api(parent_page_id, page_title, icon, properties, notion_key, parent_page_type)
+ new_page_id = new_page.get("id",None)
+ if new_page_id:
+ print(f"🟢 🎉 Created {page_type} '{page_title}' inside parent_type '{parent_page_type}'")
+ new_page_link = f"https://notion.so/{new_page_id.replace('-','')}"
+ return new_page_id, page_title, new_page_link # DO NOT 'YIELD' WHEN USING AS LAMBDA
+ else:
+ print(f"🔴 Error! {new_page.get('Error','')}")
+ return None, None, None
else:
- return {}, _user_type, _curr_user_email
+ return None, None, None
+
+def send_to_notion(notion_json,notion_key,notion_page_id,notion_page_type,error_page_link,public_workspace,_action_id):
+ _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
+ _users_id = _usage_limits.get('id',None)
+ _sessions_id = SESSION_DATA.get('user').get('session_id',None)
+ _usage_limits = _usage_limits.get('usage_limits')
+ try:
+ if notion_json and type(notion_json) == dict:
+ yield error_page_link, f"""🟡 🏗️ Initialized NotionGen to Notion engine. Validating the Notion credentials..."""
+ is_invalid = preprocess_validation(notion_key,notion_page_id,notion_page_type)
+ if is_invalid:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_input": notion_json, "notion_response": {"success": False, "data": None, "error": is_invalid}}}}, "actions")
+ yield error_page_link, f"""{is_invalid} or use the [public workspace](https://notion.so/{public_workspace})."""
+ else:
+ notion_json['properties'] = {
+ 'User': {
+ "rich_text": [{
+ "text": {
+ "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
+ }]}}
+ page_type = notion_json["type"]
+ _new_page_id, _new_page_title, _new_page_link = create_notion_page(notion_json,notion_page_id,notion_page_type,notion_key)
+ if _new_page_id:
+ page_link = f"""🟡 🏗️ Notion template creation is in-progress on Notion Page: [{_new_page_title}]({_new_page_link})"""
+ yield page_link, f"🟡 🏗️ Notion Page (or Database) is successfully generated at above link. Content writing is now in-progress...."""
+ for _idx, child in enumerate(notion_json.get("children", [])):
+ block_type = child["type"]
+ yield page_link, f"""🟡 🏗️ You'll never see William Shakespeare writing a block of type '{block_type}' on Notion but NotionGen would love to give you a sneak peek while it writes..."""
+ res = notionUpdatePage_api(parent_id=_new_page_id, block_json=child, notion_access_token=notion_key, parent_block_type=page_type)
+ is_success = res.get("Success",False)
+ if not is_success:
+ yield page_link, f"""🔴 Error! Failed to process block '{block_type}' with error {res.get('Error','')}"""
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_input": notion_json, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}}}}, "actions")
+ page_link = f"""🟢 🎉 Success! NotionGen Page Link: [{_new_page_title}]({_new_page_link})"""
+ yield page_link, None
+ else:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_input": notion_json, "notion_response": {"success": False, "result":_new_page_link, "data": "Template generation without a new Notion page is not supported"}}}}, "actions")
+ yield error_page_link, f"""🔴 Error! Template generation without a new Notion page is not supported! Try again to generate a page."""
+ else:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": "No data found or invalid data"}}}, "actions")
+ yield error_page_link, f"""🔴 Error! No data found or invalid data! Click on 'Generate' & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
+ except Exception as error:
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
+ yield error_page_link, f"""🔴 Error! Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
-'''
- Email0 by f0 - Creates insightful summaries of unread emails which can be further used to clean-up dormant subscriptions & improve label rules.
-'''
-# EMAIL0 BY f0 FUNCTIONS
+# EMAIL0 APP FUNCTIONS
def get_label_info():
""" Fetches label info including messagesTotal & messagesUnread """
try:
curr_user = SESSION_DATA.get('user','')
if curr_user:
- labels = get_labels(userinfo=SESSION_DATA)
+ labels = getLabels_api(userinfo_json=SESSION_DATA)
return labels
else:
print("🔴 Error! Invalid Session. User not found!")
@@ -653,6 +692,8 @@ def get_unread_emails(label_id, num_emails, create_csv):
_last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
_max_emails_limit = 50000
gr_tab_id = 0
+ _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
+ _usage_limits = _usage_limits.get('usage_limits')
if _usage_limits:
if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
_page_limits = _usage_limits.get("pages",{}).get(str(gr_tab_id),{})
@@ -683,7 +724,6 @@ def get_unread_emails(label_id, num_emails, create_csv):
for update in get_emails(label_id, num_emails, batch_results, SESSION_DATA):
status = update[0]
- # print(status)
if 'Success' in status:
if create_csv:
success_file_paths = []
@@ -712,26 +752,21 @@ def get_unread_emails(label_id, num_emails, create_csv):
_usage_limits["pages"][str(gr_tab_id)]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
_usage_limits["default"]["remaining"] = _usage_limits["default"]["remaining"] - 1
_usage_limits["default"]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- update_data(curr_user_email, _usage_limits, table="users", row_id_type=_user_type, column="usage_limits")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"email_response": {"success": True, "result": status}}}}, "actions")
+ updateDB_api(curr_user_email, _usage_limits, table="users", row_id_type=_user_type, column="usage_limits")
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"email_response": {"success": True, "result": status}}}}, "actions")
yield status, file_paths, update[1], update[2], update[3], update[4], update[5]
else:
update = f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions."""
print(update)
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"Invalid argument types {args_types} vs valid ones {params_types}"}}}, "actions")
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"Invalid argument types {args_types} vs valid ones {params_types}"}}}, "actions")
yield update, file_paths, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
except Exception as error:
update = f"""🔴 Error fetching emails: {error}"""
print(update)
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": str(error)}}}, "actions")
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": str(error)}}}, "actions")
yield update, file_paths, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
-def email0_to_notion(tables,header_rows,row_limits,table_names,page_title,notion_creds):
- '''
- OBJECTIVE: Sends data to a new notion page
- ERROR: notion_client.errors.APIResponseError: body failed validation: body.children[0].table.children.length should be ≤ `100`, instead was `109`.
- CURR_SOL: Putting a cap of top 20 rows
- '''
+def email0_to_notion(tables,header_rows,row_limits,table_names,page_title,notion_creds,error_page_link):
_action_id = "email0_send_to_notion"
_usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
_users_id = _usage_limits.get('id',None)
@@ -756,351 +791,58 @@ def email0_to_notion(tables,header_rows,row_limits,table_names,page_title,notion
tables_json.append(
{"type": "table", "rows": [header_rows[idx_]] + table[:row_limits[idx_]]})
if len(tables_json) == 2*len(tables):
- # TODO - New Page or Append to Existing Page
page_json = {
'type': 'page', 'title': page_title, 'icon': '📬',
- 'children': tables_json,
- 'properties': {
- 'User': {
- "rich_text": [{
- "text": {
- "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
- }]}
- }}
+ 'children': tables_json}
notion_key, notion_page_id, notion_page_type = notion_creds
- is_invalid = preprocess_validation(notion_key,notion_page_id,notion_page_type)
- if is_invalid:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_response": {"success": False, "data": None, "error": is_invalid}}}}, "actions")
- return f"""{is_invalid} or use the [public workspace](https://notion.so/{PUBLIC_NOTION_PAGE_ID})."""
- _new_page_id, _new_page_title, _new_page_link = to_notion(page_json,notion_key,notion_page_id,notion_page_type)
- print(f"""🟢 🎉 Success! Generated Notion Page Link: [{_new_page_title}]({_new_page_link})""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_response": {"success": True, "result":_new_page_link, "data": "Email0 Analyses is successfully sent to Notion"}}}}, "actions")
- page_link = f"""🟢 🎉 Success! Generated Notion Page Link: [{_new_page_title}]({_new_page_link})"""
- return page_link # DO NOT 'YIELD' WHEN USING AS LAMBDA
+ for _page_link, _progress in send_to_notion(page_json,notion_key,notion_page_id,notion_page_type,error_page_link,PUBLIC_NOTION_PAGE_ID,_action_id=_action_id):
+ yield _page_link, _progress
else:
- print(f"""🔴 Error! No data found or invalid data! Generate analysis & then send to Notion.""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": f"No data found or invalid data"}}}, "actions")
- return f"""🔴 Error! No data found or invalid data! Generate analysis & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
+ # print(f"""🔴 Error! No data found or invalid data! Generate analysis & then send to Notion.""")
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": f"No data found or invalid data"}}}, "actions")
+ yield error_page_link, f"""🔴 Error! No data found or invalid data! Generate analysis & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
else:
- print(f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions.""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": f"Invalid argument types {args_types} vs valid ones {params_types}"}}}, "actions")
- return f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
+ # print(f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions.""")
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": f"Invalid argument types {args_types} vs valid ones {params_types}"}}}, "actions")
+ yield error_page_link, f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
except Exception as error:
- print(f"""🔴 Error! Unable to send data to Notion: {error}""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
- return f"""🔴 Error! Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
-
-# def reauthenticate_gmail():
-# """ Authenticates with Gmail API and returns the service object """
-# # print(SESSION_DATA)
-# service = authenticate_gmail(userinfo=SESSION_DATA,refresh=True)
-# return service
-
-
-'''NotionGen'''
-KEYS = {
- 'NOTION_KEY': ADMIN_NOTION_KEY,
- 'NOTION_PAGE_ID': ADMIN_NOTION_PAGE_ID,
- 'UNSPLASH_ACCESS_KEY': UNSPLASH_ACCESS_KEY,
- 'OPENAI_API_KEY': OPENAI_API_KEY,
- 'MODEL_NAME': MODEL_NAME,
- 'HUGGINGFACEHUB_API_TOKEN': HUGGINGFACEHUB_API_TOKEN
- }
-VISIBLE_PART = 1/8
-VISIBLE_PART_KEYS = {
- _key: _value[:round(len(_value)*VISIBLE_PART)]+'X'*(len(_value)-round(len(_value)*VISIBLE_PART)) for _key, _value in KEYS.items()}
-ADDITIONAL_INPUTS = [
- ["NOTION_KEY",VISIBLE_PART_KEYS['NOTION_KEY'],'https://www.notion.so/my-integrations'],
- ["NOTION_PAGE_ID",VISIBLE_PART_KEYS['NOTION_PAGE_ID'],"https://www.notion.so/{ACCOUNT_DOMAIN}/{PAGETITLE}-{PAGEID}?"],
- ["UNSPLASH_ACCESS_KEY",VISIBLE_PART_KEYS['UNSPLASH_ACCESS_KEY'],"https://unsplash.com/oauth/applications"],
- ["OPENAI_API_KEY",VISIBLE_PART_KEYS['OPENAI_API_KEY'],"https://platform.openai.com/api-keys"],
- ["MODEL_NAME",VISIBLE_PART_KEYS['MODEL_NAME'],"https://platform.openai.com/finetune"],
- ["HUGGINGFACEHUB_API_TOKEN",VISIBLE_PART_KEYS['HUGGINGFACEHUB_API_TOKEN'],"https://huggingface.co/settings/tokens"]
- ]
-VISIBLE_KEYS = deepcopy(VISIBLE_PART_KEYS)
-KEYS_NOT_REQUIRED_AS_INPUTS = ['MODEL_NAME']
-for _k in KEYS_NOT_REQUIRED_AS_INPUTS:
- VISIBLE_KEYS.pop(_k, None)
-ADDITIONAL_INPUTS = [_input for _input in ADDITIONAL_INPUTS if _input[0] not in KEYS_NOT_REQUIRED_AS_INPUTS]
-
-def private_api(description, llm, model, temperature, top_p, autosend_to_notion, key_values, notion_page_type, gr_tab_id, force_json=True, def_env_var=False, auto_restart=False, dev_mode=True):
- _query = {"description": description, "llm": llm, "model": model,
- "temperature": temperature, "top_p": top_p, "force_json": force_json,
- "def_env_var": def_env_var, "auto_restart": auto_restart, "dev_mode": dev_mode,
- "autosend_to_notion": autosend_to_notion, "notion_page_type": notion_page_type}
- _rem_limits = 1
- _speed_break_limit_seconds = 300
- _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
- gr_tab_id = 1
- _action_id = "notiongen_generate"
- _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
- _users_id = _usage_limits.get('id',None)
- _sessions_id = SESSION_DATA.get('user').get('session_id',None)
- _usage_limits = _usage_limits.get('usage_limits')
- if _usage_limits:
- if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
- _page_limits = _usage_limits.get("pages",{}).get(str(gr_tab_id),{})
- _rem_limits = _page_limits.get("remaining",0)
- _speed_break_limit_seconds = _page_limits.get("speed_break",300)
- _last_used_at = _page_limits.get("last_used_at",None)
- else:
- _default_limits = _usage_limits.get("default",{})
- _rem_limits = _default_limits.get("remaining",0)
- _speed_break_limit_seconds = _default_limits.get("speed_break",300)
- _last_used_at = _default_limits.get("last_used_at",None)
- if _last_used_at:
- _last_used_at = datetime.datetime.strptime(_last_used_at, "%Y-%m-%d %H:%M:%S")
- else:
- _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
- if _rem_limits > 0 and _last_used_at < datetime.datetime.now() - datetime.timedelta(seconds=int(_speed_break_limit_seconds)):
- _auto_restart = False
- try:
- if not dev_mode:
- actual_values = {
- 'UNSPLASH_ACCESS_KEY': UNSPLASH_ACCESS_KEY,
- 'OPENAI_API_KEY': OPENAI_API_KEY,
- 'HUGGINGFACEHUB_API_TOKEN': HUGGINGFACEHUB_API_TOKEN}
- for key in ['UNSPLASH_ACCESS_KEY','OPENAI_API_KEY','HUGGINGFACEHUB_API_TOKEN']:
- if key in key_values['Key'].values:
- key_values.loc[key_values['Key'] == key, 'Value'] = actual_values[key]
- required_keys = list(VISIBLE_KEYS.keys())
- _keys = key_values[key_values['Key'] != '']['Key'].dropna().tolist()
- _values = key_values[key_values['Value'] != '']['Value'].dropna().tolist()
- _keys_with_missing_values = key_values[(key_values['Value'] == '') | (key_values['Value'].isna())]['Key'].dropna().tolist()
- if ((not _keys) or len(_keys) < len(required_keys)) and not def_env_var:
- missing_keys = [_req_k for _req_k in required_keys if _req_k not in _keys]
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"{missing_keys} keys are missing in the inputs"}}}, "actions")
- yield f"🔴 KEY ERROR: {missing_keys} keys are missing in the inputs. Before clicking on the `Run` button, ensure all these Keys '{required_keys}' are in the Key column of the inputs.", """""", {"error": "Failed to set environment variables due to missing keys."}
- elif ((not _values) or len(_values) < len(required_keys)) and not def_env_var:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"{_keys_with_missing_values} keys in the inputs are empty"}}}, "actions")
- yield f"🔴 VALUE ERROR: {_keys_with_missing_values} keys in the inputs are empty. Before clicking on the `Run` button, ensure that a valid value is provided in the Value column of the inputs, against all these Keys '{required_keys}'. For detailed instructions to get the value(s), refer to below instructions.", """""", {"error": "Failed to set environment variables due to empty values."}
- else:
- if not def_env_var:
- for _idx, _key in enumerate(key_values['Key'].tolist()):
- if _key not in required_keys:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"Given Key '{_key}' is invalid"}}}, "actions")
- yield f"🔴 KEY ERROR: Given Key '{_key}' is invalid. Valid Keys are {required_keys}.", """""", {"error": f"Failed to set environment variables due to invalid key '{_key}'."}
- return
- n = 0
- for _idx, _key in enumerate(key_values['Key'].tolist()):
- _value = key_values.loc[key_values['Key'] == _key]['Value'].values[-1]
- yield f"🟡 🏗️ Setting variable '{_key}'", """""", {"message": f"Setting variable '{_key}'"}
- if _value not in VISIBLE_PART_KEYS.values():
- os.environ[_key] = _value
- else:
- os.environ[_key] = KEYS[_key]
- n += 1
- time.sleep(1)
- if n > 0 and _idx + 1 == len(key_values['Key'].tolist()):
- time.sleep(1)
- yield f"🟡 🏗️ Environment variables are set successfully.", """""", {"message": "Environment variables are set successfully. Let's generate the notion template."}
- _notion_key = os.getenv('NOTION_KEY')
- cumulative_content = ""
- _model = model
- if not def_env_var:
- if model and model != '':
- if model == VISIBLE_PART_KEYS['MODEL_NAME']:
- _model = KEYS['MODEL_NAME']
- else:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": "LLM Model can't be empty"}}}, "actions")
- yield f"🔴 VALUE ERROR: LLM Model can't be empty.", """""", {"error": "Failed to generate or process the NotionGen template due to error LLM Model can't be empty."}
- return
- else:
- _model = KEYS['MODEL_NAME']
- # print(description, llm, _model, force_json, temperature, top_p, def_env_var)
- for update in generate_blueprint(description, force_json, temperature, top_p, llm, _model, def_env_var):
- if isinstance(update, dict):
- blueprint_json = update.get('blueprint', {})
- _titles = re.findall(r'titled "(.*?)"', cumulative_content)
- _title = _titles[0] if _titles else "Uncategorized"
- if _usage_limits:
- if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
- _usage_limits["pages"][str(gr_tab_id)]["remaining"] = _usage_limits["pages"][str(gr_tab_id)]["remaining"] - 1
- _usage_limits["pages"][str(gr_tab_id)]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- _usage_limits["default"]["remaining"] = _usage_limits["default"]["remaining"] - 1
- _usage_limits["default"]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- update_data(curr_user_email, _usage_limits, table="users", row_id_type=_user_type, column="usage_limits")
- _auto_restart = auto_restart
- if autosend_to_notion:
- yield "🟢 🎉 NotionGen template generation is completed. 🟡 🏗️ Now, sending the template to Notion...", """""", blueprint_json
- if not def_env_var:
- parent_page_id = os.getenv('NOTION_PAGE_ID')
- else:
- parent_page_id = ADMIN_NOTION_PAGE_ID
- is_invalid = preprocess_validation(_notion_key,parent_page_id,notion_page_type)
- if is_invalid:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": cumulative_content, "data": blueprint_json}, "notion_response": {"success": False, "data": None, "error": is_invalid}},"title":_title}}, "actions")
- yield f"🟢 🎉 NotionGen template is successfully generated but failed to be sent to Notion due to below error!", f"""{is_invalid} or use the public workspace.""", blueprint_json
- else:
- blueprint_json['properties'] = {
- 'User': {
- "rich_text": [{
- "text": {
- "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
- }]}}
- for notion_progress in to_notion_new(blueprint_json,_notion_key,parent_page_id,notion_page_type):
- _progress, _new_page_id, _new_page_title, _new_page_link = notion_progress
- if "error" in _progress.lower() or 'unsupported' in _progress.lower():
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": cumulative_content, "data": blueprint_json}, "notion_response": {"success": False, "data": None, "error": _progress}},"title":_title}}, "actions")
- yield f"🟢 🎉 NotionGen template is successfully generated but failed to sent it to Notion due to below error!", f"""🔴 {_progress}. You can try again to generate a page instead.""", blueprint_json
- elif _progress == 'page' or _progress == 'database':
- yield f"🟡 🏗️ Notion Page (or Database) is successfully generated & content writing is initiated....", f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation: {_new_page_title}""", blueprint_json
- elif _progress == 'end':
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": cumulative_content, "data": blueprint_json}, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}},"title":_title}}, "actions")
- yield f"🟢 🎉 NotionGen template is successfully sent to Notion!", f"""🟢 🎉 Check out the NotionGen-generated page: {_new_page_title}""", blueprint_json
- else:
- yield f"🟡 🏗️ Notion Page (or Database) is successfully generated & content writing is in-progress for a notion block of type '{_progress}'....", f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation: {_new_page_title}""", blueprint_json
- else:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": cumulative_content, "data": blueprint_json}},"title":_title}}, "actions")
- yield "🟢 🎉 NotionGen template generation is completed. Now, you can 'Send to Notion' (go to Notion Settings section at the end).", """""", blueprint_json
- else:
- cumulative_content += update
- yield cumulative_content, """""", {"message": "NotionGen template generation in progress...."}
- except Exception as e:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": str(e)}}}, "actions")
- yield f"🔴 Error encountered: {str(e)}. Ensure that the 'Inputs' are correctly filled. Run again.", """""", {"error": f"Failed to generate or process NotionGen template due to error {e}"}
- if _auto_restart == True:
- time.sleep(5)
- yield f"🟡 🔂 Running again...", """""", {"message": "Generating a template again..."}
- yield from private_api(description, llm, model, temperature, top_p, autosend_to_notion, key_values, notion_page_type, gr_tab_id, force_json, def_env_var, auto_restart, dev_mode)
- else:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"usage_limit exceeded or reused before the cooling-off period {_speed_break_limit_seconds} (last used at {_last_used_at})"}}}, "actions")
- yield f"🔴 ⌛ Usage limit exceeded or reuse with a break of {_speed_break_limit_seconds} seconds (last used at {_last_used_at}). Please contact us to generate more content.", """""", {"error": "Usage limit exceeded. Please contact us to generate more content."}
+ # print(f"""🔴 Error! Unable to send data to Notion: {error}""")
+ insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
+ yield error_page_link, f"""🔴 Error! Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
-def preprocess_validation(notion_key,notion_page_id,notion_page_type):
- # TODO - Put validation of notion page id & notion key formats
- if not notion_key:
- update = f"""🔴 Error! Connect Notion"""
- print(update)
- return update
- if not notion_page_id:
- update = f"""🔴 Error! Select a parent Notion page/database"""
- print(update)
- return update
- if notion_page_type == 'root':
- update = f"""🔴 Error! Select a non-root page/database"""
- print(update)
- return update
- return None
-
-def ai_output_to_notion_new(blueprint_json,notion_creds):
- _action_id = "notiongen_send_to_notion"
- _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
- _users_id = _usage_limits.get('id',None)
- _sessions_id = SESSION_DATA.get('user').get('session_id',None)
- _usage_limits = _usage_limits.get('usage_limits')
- try:
- if blueprint_json and type(blueprint_json) == dict:
- notion_key, notion_page_id, notion_page_type = notion_creds
- is_invalid = preprocess_validation(notion_key,notion_page_id,notion_page_type)
- if is_invalid:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"llm_response": {"success": True, "data": blueprint_json}, "notion_response": {"success": False, "data": None, "error": is_invalid}}}}, "actions")
- yield f"""{is_invalid} or use the public workspace."""
- else:
- blueprint_json['properties'] = {
- 'User': {
- "rich_text": [{
- "text": {
- "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
- }]}}
- for notion_progress in to_notion_new(blueprint_json,notion_key,notion_page_id,notion_page_type):
- _progress, _new_page_id, _new_page_title, _new_page_link = notion_progress
- if "error" in _progress.lower() or 'unsupported' in _progress.lower():
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"llm_response": {"success": True, "data": blueprint_json}, "notion_response": {"success": False, "data": None, "error": _progress}}}}, "actions")
- yield f"""🔴 Error! {_progress}. You can try again to generate a page instead."""
- elif _progress == 'page' or _progress == 'database':
- yield f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation while it writes for you: {_new_page_title}"""
- elif _progress == 'end':
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"llm_response": {"success": True, "data": blueprint_json}, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}}}}, "actions")
- yield f"""🟢 🎉 Success! Check out the NotionGen-generated page: {_new_page_title}"""
- else:
- yield f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation while it writes (notion block of type '{_progress}') for you: {_new_page_title}"""
- else:
- print(f"""🔴 Error! No data found or invalid data! Click on 'Generate' & then send to Notion.""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": "No data found or invalid data"}}}, "actions")
- yield f"""🔴 Error! No data found or invalid data! Click on 'Generate' & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
- except Exception as error:
- print(f"""🔴 Error! Unable to send data to Notion: {error}""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
- yield f"""🔴 Error! Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
-
-def ai_output_to_notion(blueprint_json,notion_creds):
- _action_id = "notiongen_send_to_notion"
- _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
- _users_id = _usage_limits.get('id',None)
- _sessions_id = SESSION_DATA.get('user').get('session_id',None)
- _usage_limits = _usage_limits.get('usage_limits')
- try:
- if blueprint_json and type(blueprint_json) == dict:
- notion_key, notion_page_id, notion_page_type = notion_creds
- is_invalid = preprocess_validation(notion_key,notion_page_id,notion_page_type)
- if is_invalid:
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"llm_response": {"success": True, "data": blueprint_json}, "notion_response": {"success": False, "data": None, "error": is_invalid}}}}, "actions")
- return f"""{is_invalid} or use the [public workspace](https://notion.so/{NOTIONGEN_PUBLIC_PAGE_ID})."""
- else:
- blueprint_json['properties'] = {
- 'User': {
- "rich_text": [{
- "text": {
- "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
- }]}}
- _new_page_id, _new_page_title, _new_page_link = to_notion(blueprint_json,notion_key,notion_page_id,notion_page_type)
- print(f"""🟢 🎉 Success! Generated Notion Page Link: [{_new_page_title}]({_new_page_link})""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"llm_response": {"success": True, "data": blueprint_json}, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}}}}, "actions")
- page_link = f"""🟢 🎉 Success! Generated Notion Page Link: [{_new_page_title}]({_new_page_link})"""
- return page_link # DO NOT 'YIELD' WHEN USING AS LAMBDA
- else:
- print(f"""��� Error! No data found or invalid data! Click on 'Generate' & then send to Notion.""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": "No data found or invalid data"}}}, "actions")
- return f"""🔴 Error! No data found or invalid data! Click on 'Generate' & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
- except Exception as error:
- print(f"""🔴 Error! Unable to send data to Notion: {error}""")
- data, count = insert_data({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
- return f"""🔴 Error! Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
-
-def get_sample_queries(_action_id="notiongen_generate", data=[], data_type=''):
- if not data:
- data, count = check_data(None,"id, created_at, action","actions","users_id",null_check=True)
- data_type = 'SAMPLE'
- _sample_queries = {}
- _sample_titles = {}
- filtered_data = [item for item in data if item.get("action", {}).get("id") == _action_id]
- sorted_data = sorted(filtered_data, key=lambda x: x['created_at'], reverse=True)
- for _q in sorted_data:
- _query = _q.get('action',{}).get('query',{}).get('description','')
- if _query not in _sample_queries.keys():
- _result = _q.get('action',{}).get('response',{}).get('llm_response',{}).get('result','')
- if _result:
- _sample_queries[_query] = _result
- _sample_titles[_query] = f'[{data_type}] ' + _q.get('action').get('title')
- return _sample_queries, _sample_titles
+def get_sample_queries(_action_id="notiongen_generate",data=[],data_type=''):
+ if not data:
+ data = checkDB_api(row_id_value=None,column="id, created_at, action",table="actions",row_id_type="users_id",null_check=True)
+ data_type = 'SAMPLE'
+ _sample_queries = {}
+ _sample_titles = {}
+ filtered_data = [item for item in data if item.get("action", {}).get("id") == _action_id]
+ sorted_data = sorted(filtered_data, key=lambda x: x['created_at'], reverse=True)
+ for _q in sorted_data:
+ _query = _q.get('action',{}).get('query',{}).get('description','')
+ if _query not in _sample_queries.keys():
+ _result = _q.get('action',{}).get('response',{}).get('llm_response',{}).get('result','')
+ if _result:
+ _sample_queries[_query] = _result
+ _sample_titles[_query] = f'[{data_type}] ' + _q.get('action').get('title')
+ return _sample_queries, _sample_titles
def get_user_queries(_action_id="notiongen_generate"):
_user_queries = {}
_user_titles = {}
_sessions_id = SESSION_DATA.get('user',{}).get('session_id',None)
- data, count = check_data(_sessions_id,"users_id","sessions","id")
+ data = checkDB_api(_sessions_id,"users_id","sessions","id")
if data:
- data, count = check_data(data[0].get('users_id'),"id, created_at, action","actions","users_id")
+ data = checkDB_api(data[0].get('users_id'),"id, created_at, action","actions","users_id")
if data:
_user_queries, _user_titles = get_sample_queries(_action_id,data,data_type='USER')
return _user_queries, _user_titles
def get_queries_count(_action_id="notiongen_generate"):
- data, count = check_data(column="id, users_id, created_at, action",table="actions",all=True)
+ data = checkDB_api(column="id, users_id, created_at, action",table="actions",all=True)
filtered_data = [item for item in data if item.get("action", {}).get("id") == _action_id and item.get('users_id') is not None]
return len(filtered_data)
-# def get_public_queries(_action_id="notiongen_generate"):
-# _public_queries = {}
-# _public_titles = {}
-# data, count = check_data(column="id, users_id, created_at, action",table="actions",all=True)
-# filtered_data = [item for item in data if item.get("action", {}).get("id") == _action_id and item.get('users_id') is not None]
-# if filtered_data:
-# # FETCH PAGE_IDS FROM NOTION PUBLIC WORKSPACE
-# # FILTER data FOR PAGE_IDS FETCHED IN PREV STEP
-# _public_queries, _public_titles = get_sample_queries(_action_id,filtered_data,data_type='USER')
-# return _public_queries, _public_titles
# APP PAGES (GRADIO)
with gr.Blocks(
@@ -1110,7 +852,95 @@ with gr.Blocks(
notion_settings_choices = ['🟢 Live', '🟠 Live (No Page Found)', '🔴 Disconnected','🟢 Live (Public)'] # Define choices as a list of strings
with gr.Tabs(selected=1) as tabs:
- with gr.TabItem("Email0 by f0",id=0) as email0:
+ with gr.TabItem("NotionGen by f0", id=1) as notiongen:
+ gr.Markdown(""" """)
+ with gr.Row():
+ with gr.Column(scale=1):
+ main_app.load(greet, None, gr.Markdown())
+ gr.Markdown("""With *a simple prompt*, NotionGen helps *individuals, writers, influencers, professionals, builders & founders* generate *detailed and structured Notion pages/templates* using the advanced capabilities of natural language processing technology (OpenAI). Stop bookmarking *I wish I knew this before...* social media posts, kick-start that vacation or business idea with the advice of multiple subject matter experts. Let's get started on *Structured & Actionable Notion Pages with NotionGen (by f0)* journey.
""")
+ with gr.Column(scale=0):
+ user_limits1 = gr.DataFrame()
+ # gr.Image(value='data/images/logo.png', type='filepath', scale=0, show_download_button=False, container=False)
+
+ with gr.Row():
+ gr.Column()
+ with gr.Column():
+ gr.Markdown("""# NotionGen by [f0](https://linkedin.com/company/finding0)""")
+ with gr.Column(variant='panel'):
+ notiongen_pages_counter = gr.Markdown(value=f"NotionGen Pages: Unknown",elem_classes='right_text',show_label=False)
+ gr.Markdown(""" """)
+ gr.Markdown("""---""")
+
+ with gr.Row():
+ with gr.Column():
+ description = gr.Textbox(label="Describe your Notion page*", value="Generate me a detailed and comprehensive Notion page to plan a marketing campaign for an oral care brand targeted towards millennials in India.")
+ sample_descriptions = gr.Dropdown(label="Sample prompts to get started",interactive=True,multiselect=False,allow_custom_value=True,filterable=True)
+ with gr.Row():
+ llm_client = gr.Dropdown(label="Select your Expert Community*", choices=['NotionGen','Reforge','GrowthX','ChatPRD'], multiselect=False, allow_custom_value=True, value='NotionGen')
+ model = gr.Dropdown(label="Select the Community Model*", choices=[('GPT 3.5 Turbo','gpt-3.5-turbo')], multiselect=False, allow_custom_value=True, value='gpt-3.5-turbo')
+ with gr.Column(variant='panel'):
+ with gr.Row():
+ autosend_to_notion = gr.Checkbox(label="Auto-send to Notion", value=False, container=False, scale=2, info="Select Notion page or use public workspace")
+ public_workspace_checkbox2 = gr.Checkbox(label=f"Use Public Workspace", value=False, container=False, scale=0, info="To test NotionGen", elem_classes='right_btn')
+ user_notion_page_id2 = gr.Dropdown(label="Select Notion Page",choices=[],value=None,scale=0,allow_custom_value=False,multiselect=False,interactive=True)
+ with gr.Row():
+ refresh_notion_settings_btn2 = gr.Button(value=f"Refresh Notion Pages", scale=0, size='sm')
+ gr.Markdown(value=f"""[CheckOut Public Workspace](https://notion.so/{NOTIONGEN_PUBLIC_PAGE_ID})""",elem_classes='right_text')
+
+ with gr.Accordion("Advanced Settings", open=False):
+ with gr.Row():
+ temperature = gr.Slider(label="Creativity Score (Temperature)", minimum=0.1, maximum=1.0, step=0.1, value=0.7, info="Make the model more creative.")
+ top_p = gr.Slider(label="Lateral Thinking (Top P)", minimum=0.1, maximum=1.0, step=0.1, value=0.2, info="Out of box thinking.")
+ with gr.Row():
+ use_default_env_vars = gr.Checkbox(label="Use Default Environment Variables", value=False, visible=False)
+ auto_restart = gr.Checkbox(label="Auto-restart (if failed)", value=False, visible=False)
+ with gr.Row():
+ dev_mode = gr.Checkbox(label="Developer Mode", value=False, interactive=True, info="Bring your own API keys", visible=False)
+ force_json = gr.Checkbox(label="Force JSON (LLM response)", value=True, visible=False)
+ additional_inputs = gr.DataFrame(
+ label="Input the values. Use references or scroll down for step-wise instructions.",
+ headers=["Key","Value","Reference"],
+ datatype=["str","str","str"],
+ value=ADD_INPUTS,
+ row_count=(len(ADD_INPUTS),'fixed'),
+ col_count=(3,'fixed'),
+ wrap=True,
+ visible=False)
+ submit_btn = gr.Button("Generate",variant='primary')
+
+ with gr.Column(variant='panel'):
+ html_output = gr.HTML(label="Notion Page Generation Status (if auto-send to notion is selected)",value=f"""🟡 🏗️ Sample NotionGen Page Link: {SAMPLE_NOTIONGEN_PAGE_NAME} [SAMPLE]""")
+ status_output = gr.Text(label="Status",placeholder="Here, you will see how NotionGen creates magic.",show_copy_button=True)
+
+ models_lib = gr.JSON(label="Community Models Library",visible=False)
+ notionJSON_output = gr.JSON(label="NotionGen Template JSON",visible=False)
+ samples_lib = gr.JSON(label="Sample Input<>Output Library",visible=False)
+
+ gr.Markdown(""" """)
+ with gr.Column(variant='panel',scale=0):
+ with gr.Row():
+ gr.Markdown("""#### ⬇️ Notion Settings""")
+ notion_settings_status2 = gr.Markdown(notion_settings_choices[2],elem_classes='right_text')
+ with gr.Row():
+ with gr.Column(scale=0):
+ notion_page_max_depth2 = gr.Slider(maximum=10,minimum=1,value=2,step=1,label="Notion Page Max Depth",interactive=True,scale=0)
+ with gr.Column(scale=2):
+ to_notion_btn2 = gr.Button('Send to Notion 🔴', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='lg', interactive=True, elem_classes='center_btn')
+ with gr.Column(scale=0):
+ connect_to_notion2 = gr.Button(link=NOTION_AUTHORIZATION_ENDPOINT, value='Connect 🟠', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm',elem_classes='right_btn')
+ refresh_notion_conn_btn = gr.Button(value=f"Refresh Notion Connection", interactive=False, scale=0, size='sm', elem_classes='right_btn')
+ with gr.Row():
+ gr.Column(scale=0)
+ with gr.Column(scale=1):
+ notiongen_page_link = gr.Markdown(value=f"""🎉 Sample NotionGen Page Link: [{SAMPLE_NOTIONGEN_PAGE_NAME} [SAMPLE]](https://www.notion.so/{SAMPLE_NOTIONGEN_PAGE_ID})""", elem_classes='center_text')
+ to_notion_update2 = gr.Markdown(value=None, elem_classes='center_text')
+ gr.Column(scale=0)
+ user_notion_access_token2 = gr.Dropdown(label="Your Notion Integration API Token",choices=[],value=None,interactive=False,visible=False)
+ selected_page_type2 = gr.Dropdown(label="Selected Page Type",choices=['page','database','root'],value=None,interactive=True,visible=False)
+ user_notion_page_types2 = gr.List(label="Page Types",value=None,scale=0,interactive=True,visible=False)
+
+
+ with gr.TabItem("Email0 by f0",id=0,interactive=False) as email0:
gr.Markdown(""" """)
with gr.Row():
with gr.Column(scale=1):
@@ -1139,7 +969,7 @@ with gr.Blocks(
max_emails_slider = gr.Slider(label="Number of Emails*", minimum=0, maximum=max_emails, step=5, value=10, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{max_emails.value} with increments being half of default value.'", show_label=True)
create_csv_checkbox = gr.Checkbox(label="Create CSV/Excel", info="[Optional] If analysis is required in csv files, select this option. Once downloaded, each csv will be instantly deleted.", value=False)
analyze_btn = gr.Button('Analyse', variant='primary', scale=0, elem_classes='center_btn')
-
+
with gr.Column():
gr.Markdown("""## 🏷️ Label-wise Summary""")
with gr.Column(variant='panel'):
@@ -1157,26 +987,31 @@ with gr.Blocks(
download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[5], elem_classes='center_btn')
gr.Markdown("""### OR""", elem_classes='center_text')
with gr.Row():
- with gr.Column(scale=0):
- notion_settings_status = gr.Markdown(notion_settings_choices[2])
+ gr.Column(scale=0)
with gr.Column(scale=2):
to_notion_btn = gr.Button('Send to Notion 🔴', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm', interactive=True, elem_classes='center_btn')
with gr.Column(scale=0):
- user_notion_page_id = gr.Dropdown(label="Select Notion Page",choices=[],value=None,scale=0,allow_custom_value=False,multiselect=False,interactive=True,container=False)
+ notion_settings_status = gr.Markdown(notion_settings_choices[2], elem_classes='right_text')
with gr.Row():
- with gr.Column(scale=0):
- connect_to_notion = gr.Button(link=NOTION_AUTHORIZATION_ENDPOINT, value='Connect 🟠', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm')
+ with gr.Column():
refresh_notion_settings_btn = gr.Button(value=f"Refresh Notion Pages", scale=0, size='sm')
- with gr.Column(scale=1):
- to_notion_update = gr.Markdown(value=f"""🎉 Generated Notion Page Link: [Unread Emails Analysis [SAMPLE]](https://www.notion.so/dfe758094f5e47d99e51e1bd9db195a9)""", elem_classes='center_text')
- with gr.Column(scale=0,elem_classes='right_btn'):
- notion_page_max_depth = gr.Slider(maximum=10,minimum=1,value=2,step=1,label="Notion Page Max Depth",interactive=True,scale=0,visible=False)
+ with gr.Column():
+ user_notion_page_id = gr.Dropdown(label="Select Notion Page",choices=[],value=None,scale=0,allow_custom_value=False,multiselect=False,interactive=True,container=False)
+ with gr.Column():
public_workspace_checkbox = gr.Checkbox(label=f"Use Public Workspace", value=False, container=False, scale=0, elem_classes='right_btn')
gr.Markdown(value=f"""[CheckOut Public Workspace](https://notion.so/{PUBLIC_NOTION_PAGE_ID})""", elem_classes='right_text')
+ with gr.Row():
+ with gr.Column(scale=0):
+ notion_page_max_depth = gr.Slider(maximum=10,minimum=1,value=2,step=1,label="Notion Page Max Depth",interactive=True,scale=0)
+ with gr.Column(scale=1):
+ email0_page_link = gr.Markdown(value=f"""🎉 Sample Email0 Notion Page Link: [{SAMPLE_EMAIL0_PAGE_NAME} [SAMPLE]](https://www.notion.so/{SAMPLE_EMAIL0_PAGE_ID})""", elem_classes='center_text')
+ to_notion_update = gr.Markdown(value=None, elem_classes='center_text')
+ with gr.Column(scale=0):
+ connect_to_notion = gr.Button(link=NOTION_AUTHORIZATION_ENDPOINT, value='Connect 🟠', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm', elem_classes='right_btn')
user_notion_access_token = gr.Dropdown(label="Your Notion Integration API Token",choices=[],value=None,interactive=False,visible=False)
selected_page_type = gr.Dropdown(label="Selected Page Type",choices=['page','database','root'],value=None,interactive=True,visible=False)
user_notion_page_types = gr.List(label="Page Types",value=None,scale=0,interactive=True,visible=False)
-
+
gr.Markdown(""" """)
with gr.Row():
with gr.Column(variant='panel'):
@@ -1184,7 +1019,7 @@ with gr.Blocks(
gr.Markdown("""#### 💌 Domain-wise Summary""")
domain_analysis_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[1])
domain_analysis = gr.DataFrame(label="""Email count by Domain would be shown here!""",headers=[col+'_SAMPLE' for col in EMAIL_SUMMARY_COLS],value=EMAIL_SUMMARY_DB.values.tolist(),type='array',col_count=(len(EMAIL_SUMMARY_COLS),'fixed'),interactive=False,height=216)
-
+
with gr.Column(variant='panel'):
with gr.Row():
gr.Markdown("""#### 📩 Sender-wise Summary""")
@@ -1212,248 +1047,17 @@ with gr.Blocks(
email_processing_errors_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[4])
error_emails = gr.DataFrame(label="""Emails with errors during processing""",headers=[col+'_SAMPLE' for col in PROCESSING_ERRORS_COLS],value=PROCESSING_ERRORS_DB.values.tolist(),type='array',col_count=(len(PROCESSING_ERRORS_COLS),'fixed'),interactive=False,height=216)
- def change_labels():
- fetched_labels = get_label_info()
- if isinstance(fetched_labels,pd.DataFrame) and not fetched_labels.empty:
- _labels = fetched_labels.values.tolist()
- new_labels = [(label[1],label[0]) for label in _labels]
- default_label = new_labels[3][0]
- default_label_id = new_labels[3][1]
- def_label_max_emails = [label[3] for label in _labels if label[0] == default_label_id][0]
- step = def_label_max_emails/20
- value = int(step*2)
- return fetched_labels, gr.Dropdown(choices=new_labels, value=default_label), gr.Slider(maximum=def_label_max_emails, value=value, step=step, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{def_label_max_emails}'"), gr.Checkbox(value=False), gr.Button(value="Refresh Label Summary"), gr.Markdown(value=None), gr.Button(variant='secondary',visible=True)
- else:
- return gr.DataFrame(value=LABEL_DB.values.tolist()), gr.Dropdown(value='CATEGORY_PROMOTIONS'), gr.Slider(value=10), gr.Checkbox(value=False), gr.Button(value="Fetch Label Summary"), gr.Markdown(visible=True,value="🔴 Please connect to Gmail to fetch label summary"), gr.Button(visible=True)
- main_app.load(change_labels,None,
- [labels,labels_choices,max_emails_slider,create_csv_checkbox,get_labels_btn,get_labels_update,gmail_authenticate_btn])
- get_labels_btn.click(change_labels,None,
- [labels,labels_choices,max_emails_slider,create_csv_checkbox,get_labels_btn,get_labels_update,gmail_authenticate_btn])
-
- def update_max_emails(labels,labels_choices,def_max,evt:gr.SelectData):
- try:
- def_label_max_emails = [label[3] for label in labels if label[0] == labels_choices][0]
- except:
- def_label_max_emails = -1
- if def_label_max_emails >= 0:
- step = def_label_max_emails/20
- value = int(step*2)
- if type(def_label_max_emails) == int:
- return gr.Slider(maximum=def_label_max_emails, value=value, step=step, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{def_label_max_emails}'"), gr.Checkbox(value=False)
- else:
- return gr.Slider(maximum=def_max), gr.Checkbox(value=False)
- labels_choices.select(update_max_emails,
- [labels,labels_choices,max_emails],[max_emails_slider,create_csv_checkbox])
-
- def update_labels(labels,labels_choices,max_emails,evt:gr.SelectData):
- labels_choices = labels[evt.index[0]][evt.index[1]]
- max_emails, csv_checkbox = update_max_emails(labels,labels_choices,max_emails,evt)
- return labels_choices, max_emails, csv_checkbox
- labels.select(update_labels,[labels, labels_choices, max_emails],
- [labels_choices,max_emails_slider,create_csv_checkbox])
-
- def analyze_btn_deactivate():
- return gr.Button(interactive=False)
- get_labels_btn.click(analyze_btn_deactivate,None,analyze_btn)
-
- def analyze_btn_activate():
- return gr.Button(interactive=True)
- labels.change(analyze_btn_activate,None,analyze_btn)
-
- downloadable_file_paths = gr.DataFrame(label="Files Created for the Last Analysis",value=[FILE_PATHS],type='array',col_count=(len(FILE_PATHS),'fixed'),row_count=(1,'dynamic'),interactive=False,height=216,visible=False)
- analyze_btn.click(get_unread_emails,
- [labels_choices, max_emails_slider, create_csv_checkbox],[update, downloadable_file_paths, analysis, domain_analysis, sample_emails, unsub_links, error_emails])
-
- selected_csv_option = gr.Checkbox(value=False,visible=False)
- def last_csv_option(selected_option):
- return gr.Checkbox(value=selected_option)
- analyze_btn.click(last_csv_option,create_csv_checkbox,selected_csv_option)
-
- def download_links_update(downloadable_file_paths):
- return gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][5],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][1],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][0],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][2],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][3],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][4],interactive=True)
- downloadable_file_paths.change(download_links_update,downloadable_file_paths,
- [download_btn,domain_analysis_download_btn,sender_analysis_download_btn,emails_download_btn,unsub_links_download_btn,email_processing_errors_download_btn])
-
- def reconnect_to_gmail(analyze_status):
- if isinstance(analyze_status,str) and 'no connection with gmailapi' in analyze_status.lower():
- return gr.Button(variant='primary',visible=True)
- else:
- return gr.Button(variant='secondary',visible=True)
- update.change(reconnect_to_gmail,update,gmail_authenticate_btn)
-
- def delete(file,sample_file,analysis_status,selected_csv_option):
- file_to_delete = os.path.basename(file)
- if 'Gmail0_SAMPLE' not in file_to_delete and selected_csv_option and "or download it as csv or" in analysis_status:
- file_to_delete = os.path.join(DATA_LOCATION, file_to_delete)
- try:
- if os.path.exists(file_to_delete):
- os.remove(file_to_delete)
- print(f"File {file_to_delete} has been deleted.")
- label="Downloaded & Deleted! Now, clean your inbox?"
- else:
- label="File Not Found! Click on 'Analyse'"
- except Exception as error:
- print(f"""🔴 Error! {error}""")
- label="Facing Error! Try another time"
- else:
- label="Tick 'Create CSV/Excel', click on 'Analyse' & wait for completion!"
- return gr.DownloadButton(value=sample_file[0][0],label=label)
- download_btn.click(delete,
- [download_btn,gr.List([[FILE_PATHS[5]]],visible=False),update,selected_csv_option],download_btn)
- domain_analysis_download_btn.click(delete,
- [domain_analysis_download_btn,gr.List([[FILE_PATHS[1]]],visible=False),update,selected_csv_option],domain_analysis_download_btn)
- sender_analysis_download_btn.click(delete,
- [sender_analysis_download_btn,gr.List([[FILE_PATHS[0]]],visible=False),update,selected_csv_option],sender_analysis_download_btn)
- emails_download_btn.click(delete,
- [emails_download_btn,gr.List([[FILE_PATHS[2]]],visible=False),update,selected_csv_option],emails_download_btn)
- unsub_links_download_btn.click(delete,
- [unsub_links_download_btn,gr.List([[FILE_PATHS[3]]],visible=False),update,selected_csv_option],unsub_links_download_btn)
- email_processing_errors_download_btn.click(delete,
- [email_processing_errors_download_btn,gr.List([[FILE_PATHS[4]]],visible=False),update,selected_csv_option],email_processing_errors_download_btn)
-
- def send_to_notion_deactivate():
- return gr.Button(interactive=False)
- analyze_btn.click(send_to_notion_deactivate,None,[to_notion_btn])
-
- def send_to_notion_activate():
- return gr.Button(interactive=True)
- domain_analysis.change(
- send_to_notion_activate,None,[to_notion_btn])
-
- to_notion_btn.click(
- fn=lambda df1_, df2_, df3_, key_, page_id_, page_type_: email0_to_notion(
- [df1_, df2_, df3_], [EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_COLS, UNSUB_COLS],
- [20, 20, 20], ['Domain-wise (Top 20) Unread Emails Analysis', 'Sender-wise (Top 20) Unread Emails Analysis', 'Unsubscribe Links (Top 20) for Unread Emails'],
- 'Unread Emails Analysis '+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f"),
- [key_, page_id_, page_type_]),
- inputs=[domain_analysis, analysis, unsub_links, user_notion_access_token, user_notion_page_id, selected_page_type],
- outputs=to_notion_update)
-
gr.Markdown("""---""")
gr.Markdown("""
""")
-
- with gr.TabItem("NotionGen by f0", id=1) as notiongen:
- gr.Markdown(""" """)
- with gr.Row():
- with gr.Column(scale=1):
- main_app.load(greet, None, gr.Markdown())
- gr.Markdown("""Let's get started on *Structured & Actionable Notion Pages with NotionGen (by f0)* journey. Generate a detailed and comprehensive Notion page.
""")
- with gr.Column(scale=0):
- user_limits1 = gr.DataFrame()
- # gr.Image(value='data/images/logo.png', type='filepath', scale=0, show_download_button=False, container=False)
-
- with gr.Row():
- gr.Column()
- with gr.Column():
- gr.Markdown("""# NotionGen by [f0](https://linkedin.com/company/finding0)""")
- with gr.Column(variant='panel'):
- notiongen_pages_counter = gr.Markdown(value="NotionGen Pages: Unknown",elem_classes='right_text',show_label=False)
- gr.Markdown(""" """)
- gr.Markdown("""---""")
-
- with gr.Row():
- with gr.Column():
- description = gr.Textbox(label="Describe your Notion page*", value="Generate me a detailed and comprehensive Notion page to plan a marketing campaign for an oral care brand targeted towards millennials in India.")
- sample_descriptions = gr.Dropdown(label="Sample prompts to get started",interactive=True,multiselect=False,allow_custom_value=True,filterable=True)
- with gr.Row():
- llm_client = gr.Dropdown(label="Select your Expert Community*", choices=['NotionGen','Reforge','GrowthX','ChatPRD'], multiselect=False, allow_custom_value=True, value='NotionGen')
- model = gr.Dropdown(label="Select the Community Model*", choices=[('APT 0.1',VISIBLE_PART_KEYS['MODEL_NAME']),('GPT 3.5 Turbo','gpt-3.5-turbo')], multiselect=False, allow_custom_value=True, value=VISIBLE_PART_KEYS['MODEL_NAME'])
- with gr.Column(variant='panel'):
- with gr.Row():
- autosend_to_notion = gr.Checkbox(label="Auto-send to Notion", value=False, container=False, scale=2, info="Select Notion page or use public workspace")
- public_workspace_checkbox2 = gr.Checkbox(label=f"Use Public Workspace", value=False, container=False, scale=0, info="To test NotionGen", elem_classes='right_btn')
- user_notion_page_id2 = gr.Dropdown(label="Select Notion Page",choices=[],value=None,scale=0,allow_custom_value=False,multiselect=False,interactive=True)
- with gr.Row():
- refresh_notion_settings_btn2 = gr.Button(value=f"Refresh Notion Pages", scale=0, size='sm')
- gr.Markdown(value=f"""[CheckOut Public Workspace](https://notion.so/{NOTIONGEN_PUBLIC_PAGE_ID})""",elem_classes='right_text')
-
- with gr.Accordion("Advanced Settings", open=False):
- with gr.Row():
- temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=1.0, step=0.1, value=0.7, info="Make the model more creative.")
- top_p = gr.Slider(label="Top P", minimum=0.1, maximum=1.0, step=0.1, value=0.2, info="Out of box thinking.")
- with gr.Row():
- dev_mode = gr.Checkbox(label="Developer Mode", value=False, interactive=True, info="Bring your own API keys")
- force_json = gr.Checkbox(label="Force JSON (LLM response)", value=True, visible=False)
- use_default_env_vars = gr.Checkbox(label="Use Default Environment Variables", value=False, visible=False)
- auto_restart = gr.Checkbox(label="Auto-restart (if failed)", value=False, visible=False)
- additional_inputs = gr.DataFrame(
- label="Input the values. Use references or scroll down for step-wise instructions.",
- headers=["Key","Value","Reference"],
- datatype=["str","str","str"],
- value=ADDITIONAL_INPUTS,
- row_count=(len(ADDITIONAL_INPUTS),'fixed'),
- col_count=(3,'fixed'),
- wrap=True,
- visible=False
- )
- submit_btn = gr.Button("Generate",variant='primary')
-
- with gr.Column():
- status_output = gr.Text(label="Status",placeholder="Here, you will see how NotionGen creates magic.",value=None,show_copy_button=True)
- html_output = gr.HTML(label="Notion Page Generation Status (if auto-send to notion is selected)")
-
- models_lib = gr.JSON(label="Community Models Library",visible=False)
- notionJSON_output = gr.JSON(label="NotionGen Template JSON",visible=False)
- samples_lib = gr.JSON(label="Sample Input<>Output Library",visible=False)
-
- gr.Markdown(""" """)
- with gr.Column(variant='panel',scale=0):
- with gr.Row():
- gr.Markdown("""#### ⬇️ Notion Settings""")
- notion_settings_status2 = gr.Markdown(notion_settings_choices[2],elem_classes='right_text')
- with gr.Row():
- with gr.Column(scale=0):
- notion_page_max_depth2 = gr.Slider(maximum=10,minimum=1,value=2,step=1,label="Notion Page Max Depth",interactive=True,scale=0)
- with gr.Column(scale=2):
- to_notion_btn2 = gr.Button('Send to Notion 🔴', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='lg', interactive=True, elem_classes='center_btn')
- with gr.Column(scale=0):
- connect_to_notion2 = gr.Button(link=NOTION_AUTHORIZATION_ENDPOINT, value='Connect 🟠', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm',elem_classes='right_btn')
- gr.Markdown(value="Refresh page after connecting your Notion", elem_classes='right_text')
- with gr.Row():
- gr.Column(scale=0)
- with gr.Column(scale=1):
- to_notion_update2 = gr.Markdown(value=f"""🎉 Generated Notion Page Link: [2-Week Vacation Across India [SAMPLE]](https://www.notion.so/8d447c76a4cf4460aad2f013cd6e57ba)""", elem_classes='center_text')
- gr.Column(scale=0)
- user_notion_access_token2 = gr.Dropdown(label="Your Notion Integration API Token",choices=[],value=None,interactive=False,visible=False)
- selected_page_type2 = gr.Dropdown(label="Selected Page Type",choices=['page','database','root'],value=None,interactive=True,visible=False)
- user_notion_page_types2 = gr.List(label="Page Types",value=None,scale=0,interactive=True,visible=False)
-
- def update_autosend(token):
- if not token:
- return gr.Checkbox(value=False,interactive=False,info="Connect your Notion or use public workspace")
- return gr.Checkbox(interactive=True,info="Select Notion page or use public workspace")
- user_notion_access_token2.change(update_autosend,[user_notion_access_token2],autosend_to_notion)
- def update_interface_inputs(page_id,token):
- if token and page_id:
- key_values = deepcopy(ADDITIONAL_INPUTS)
- key_values[0][1] = token
- key_values[1][1] = page_id
- return key_values
- return ADDITIONAL_INPUTS
- user_notion_page_id2.change(update_interface_inputs,[user_notion_page_id2,user_notion_access_token2],additional_inputs)
-
- to_notion_btn2.click(
- fn=lambda json_, key_, page_id_, page_type_: ai_output_to_notion(
- json_, [key_, page_id_, page_type_]),
- inputs=[notionJSON_output,user_notion_access_token2,user_notion_page_id2,selected_page_type2],
- outputs=to_notion_update2)
-
- with gr.TabItem("Get Started", id=2) as get_started:
- gr.Markdown("""
""")
- gr.Markdown(f"""{Path('components/gradio/guides/app_intro.md').read_text()}""", elem_classes="center_text")
- gr.Markdown(f"""{Path('components/gradio/guides/get_started_guide.md').read_text()}""")
- gr.Markdown("""
""")
- gr.Markdown(f"""Only way to get started is to take the first step.""", elem_classes="center_text")
-
- with gr.TabItem("Contact Us", id=3) as contact_us:
+ with gr.TabItem("Contact Us", id=2) as contact_us:
gr.Markdown("""
""")
gr.Markdown("""# Reach out to us by clicking [here](https://www.linkedin.com/company/finding0).""")
gr.Markdown("""
""")
- with gr.TabItem("Settings", id=4) as settings:
+ with gr.TabItem("Settings", id=3) as settings:
gr.Markdown("""
""")
with gr.Column(variant='panel'):
users_username = gr.Markdown(elem_classes='center_text')
@@ -1482,237 +1086,10 @@ with gr.Blocks(
2. Navigate to 'Integrations' or 'Connected Apps' or 'Connections.
3. Find our application 'finding0' in the list and click 'Revoke Access'.""")
gr.Markdown("""
""")
-
- with gr.TabItem(label="APIs", id=5, interactive=False) as gr_apis:
- def google_auth_api(access_token_json: str, user_json: str, scope: str, session_data_json: json):
- access_token = json.loads(access_token_json)
- user = json.loads(user_json)
- session_data = json.loads(session_data_json)
- result = google_auth_db_sync(access_token, user, scope, session_data)
- return result
- googleAuth_api = gr.Interface(
- fn=google_auth_api,
- inputs=["text", "text", "text", "json"], # JSON strings for access_token and user
- outputs="json")
-
- def check_with_db_api(row_id_value: str, column: str, table: str, row_id_type: str, null_check: bool, all: bool):
- data, count = check_data(row_id_value, column, table, row_id_type, null_check, all)
- return data
- checkDB_api = gr.Interface(
- fn=check_with_db_api,
- inputs=["text", "text", "text", "text",
- gr.Checkbox(label="Null Check for Row ID", value=False),
- gr.Checkbox(label="All Rows", value=False)], # Inputs for email, column, table, and row_id_type
- outputs="json")
-
- def check_user_api(row_id_value: str, row_id_type: str):
- data, count = check_user(row_id_value, type=row_id_type)
- return data
- checkUser_api = gr.Interface(
- fn=check_user_api,
- inputs=["text", "text"], # Inputs for email & row_id_type
- outputs="json")
-
- def sync_notion_pages_api(row_id_value:str,row_id_type:str,refresh:bool,max_depth:int):
- return parse_user_pages(row_id_value,user_type=row_id_type,refresh=refresh,max_depth=max_depth)
- syncNotion_api = gr.Interface(
- fn=sync_notion_pages_api,
- inputs=["text","text",
- gr.Checkbox(label="Refresh", value=False),
- gr.Number(label="Max Depth", value=2, step=1)],
- outputs="json")
-
- def update_db_api(row_id_value:str,update_data_json:json,table:str,row_id_type:str,column:str):
- data_to_update = json.loads(update_data_json)
- data, count = update_data(row_id=row_id_value,data=data_to_update,table=table,row_id_type=row_id_type,column=column)
- return data
- updateDB_api = gr.Interface(
- fn=update_db_api,
- inputs=["text","json","text","text","text"],
- outputs="json")
-
- def notion_auth_api(access_code:str,redirect_uri:str,session_data_json:json):
- session_data = json.loads(session_data_json)
- notion_auth_db_sync(access_code,redirect_uri,session_data)
- return None
- notionAuth_api = gr.Interface(
- fn=notion_auth_api,
- inputs=["text","text","json"],
- outputs=None)
-
- def create_notionPage_api(parent_page_id:str, page_title:str, icon:str, properties_json:json, notion_access_token:str, parent_page_type:str):
- try:
- properties = json.loads(properties_json)
- new_page = create_page(parent_id=parent_page_id, title=page_title, icon=icon, properties=properties, cover_image=True, notion_key=notion_access_token, parent_type=parent_page_type)
- return new_page
- except Exception as e:
- print(str(e))
- return {"Error": str(e)}
- createNotionPage_api = gr.Interface(
- fn=create_notionPage_api,
- inputs=["text","text","text","json","text","text"],
- outputs="json")
-
- def update_notionPage_api(parent_id:str, block_json:json, notion_access_token:str, parent_block_type:str):
- try:
- block_json = json.loads(block_json)
- process_blueprint(parent_id=parent_id, block_json=block_json, notion_key=notion_access_token, parent_type=parent_block_type)
- return {"Success": True}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- updateNotionPage_api = gr.Interface(
- fn=update_notionPage_api,
- inputs=["text","json","text","text"],
- outputs="json")
-
- def invoke_llm_api(description:str,force_json:bool,temperature:float,top_p:float,llm:str,model:str,llm_key:str,def_env_var:bool,custom_data:str,api:bool):
- try:
- if api:
- response, chunks = invoke_llm(description,force_json,temperature,top_p,llm,model,llm_key,def_env_var,custom_data,api=api)
- return chunks
- else:
- response = invoke_llm(description,force_json,temperature,top_p,llm,model,llm_key,def_env_var,custom_data,api=api)
- return response
- except Exception as e:
- print(str(e))
- return {"Error": str(e)}
- invokeLLM_api = gr.Interface(
- fn=invoke_llm_api,
- inputs=["text",gr.Checkbox(),gr.Number(),gr.Number(),"text","text","text",gr.Checkbox(),"text",gr.Checkbox()],
- outputs="json")
- def get_labels_api(userinfo_json:json):
- userinfo = json.loads(userinfo_json)
- return get_labels(userinfo=userinfo)
- getLabels_api = gr.Interface(
- fn=get_labels_api,
- inputs="json",
- outputs=gr.DataFrame())
-
- def add_session_api(curr_user_id:str, id_type:str, session_json:json):
- try:
- session = json.loads(session_json)
- session_data = add_session(curr_user_id, id_type, session)
- return {"Success": True, "session_data": session_data}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- addSession_api = gr.Interface(
- fn=add_session_api,
- inputs=["text", "text", "json"],
- outputs="json")
-
- def delete_user_api(curr_user_id:str, id_type:str, session_data_json:json):
- try:
- session_data = json.loads(session_data_json)
- delete_user(curr_user_id,id_type,session_data)
- return {"Success": True}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- deleteUser_api = gr.Interface(
- fn=delete_user_api,
- inputs=["text", "text", "json"],
- outputs="json")
-
- def insert_data_api(table:str,data_json:json):
- try:
- data = json.loads(data_json)
- insert_data(data,table)
- return {"Success": True}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- insertDB_api = gr.Interface(
- fn=insert_data_api,
- inputs=["text","json"],
- outputs="json")
-
- def set_notion_settings(refresh,max_depth=2):
- token_option, page_id_option, page_types = get_connected_notion_info(refresh,max_depth=max_depth)
- if token_option:
- token = token_option[0][1]
- page_id = None
- page_type = None
- conn_status = notion_settings_choices[0]
- if page_id_option:
- to_notion_btn_val = "Send to My Notion 🟢"
- page_id = page_id_option[1][1]
- page_types = [page_types]
- page_type = update_page_type(page_id,page_types,selected_page_type)
- else:
- to_notion_btn_val = "Send to Notion 🟠"
- conn_status = notion_settings_choices[1]
- return gr.Button(value="Reconnect 🟠"), gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.Checkbox(value=False), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Button(value="Reconnect 🟠"), gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.Checkbox(value=False), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Markdown(conn_status), gr.Markdown(conn_status)
- else:
- return connect_to_notion, user_notion_access_token, user_notion_page_id, to_notion_btn, gr.Checkbox(value=True), user_notion_page_types, selected_page_type, connect_to_notion2, user_notion_access_token2, user_notion_page_id2, to_notion_btn2, gr.Checkbox(value=True), user_notion_page_types2, selected_page_type2, notion_settings_status, notion_settings_status2
- def load_notion_settings():
- return set_notion_settings(False,max_depth=notion_page_max_depth2.value)
- main_app.load(load_notion_settings,None,
- [connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status,notion_settings_status2],show_progress='minimal')
- def refresh_notion_settings(max_depth):
- return set_notion_settings(True,max_depth)
- refresh_notion_settings_btn.click(refresh_notion_settings,notion_page_max_depth,
- [connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status,notion_settings_status2])
- refresh_notion_settings_btn2.click(refresh_notion_settings,notion_page_max_depth2,
- [connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status,notion_settings_status2])
-
- def update_notion_settings(selected_public_workspace,curr_notion_status,tab_name):
- if selected_public_workspace:
- if type(tab_name) == str:
- if 'email0' in tab_name.lower():
- _public_page_type = 'database'
- return gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_KEY)], value=PUBLIC_NOTION_KEY, interactive=False), gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_PAGE_ID)], value=PUBLIC_NOTION_PAGE_ID, interactive=False), gr.Button(value="Send to Public Notion 🟢"), gr.List(value=[[('Use Public Workspace',_public_page_type)]]), gr.Dropdown(value=_public_page_type), gr.Markdown(notion_settings_choices[3]), gr.Button(visible=False), gr.Slider(visible=False)
- if 'notiongen' in tab_name.lower():
- _public_page_type = 'database'
- return gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_KEY)], value=PUBLIC_NOTION_KEY, interactive=False), gr.Dropdown(choices=[('Use Public Workspace',NOTIONGEN_PUBLIC_PAGE_ID)], value=NOTIONGEN_PUBLIC_PAGE_ID, interactive=False), gr.Button(value="Send to Public Notion 🟢"), gr.List(value=[[('Use Public Workspace',_public_page_type)]]), gr.Dropdown(value=_public_page_type), gr.Markdown(notion_settings_choices[3]), gr.Button(visible=False), gr.Slider(visible=False)
- else:
- token_option, page_id_option, page_types = get_connected_notion_info(max_depth=notion_page_max_depth2.value)
- if token_option:
- token = token_option[0][1]
- page_id = None
- page_type = None
- conn_status = notion_settings_choices[0]
- if page_id_option:
- to_notion_btn_val = "Send to My Notion 🟢"
- page_id = page_id_option[1][1]
- page_types = [page_types]
- page_type = update_page_type(page_id,page_types,selected_page_type)
- else:
- to_notion_btn_val = "Send to Notion 🟠"
- conn_status = notion_settings_choices[1]
- return gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Markdown(conn_status), gr.Button(interactive=True, visible=True), gr.Slider(visible=True, value=2)
- if type(tab_name) == str:
- if 'email0' in tab_name.lower():
- return user_notion_access_token, user_notion_page_id, to_notion_btn, user_notion_page_types, selected_page_type, notion_settings_status, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
- if 'notiongen' in tab_name.lower():
- return user_notion_access_token2, user_notion_page_id2, to_notion_btn2, user_notion_page_types2, selected_page_type2, notion_settings_status2, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
- return user_notion_access_token, user_notion_page_id, to_notion_btn, user_notion_page_types, selected_page_type, notion_settings_status, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
- public_workspace_checkbox.change(
- fn=lambda public_option_, conn_status_: update_notion_settings(
- public_option_, conn_status_, email0.label),
- inputs=[public_workspace_checkbox,notion_settings_status],
- outputs=[user_notion_access_token,user_notion_page_id,to_notion_btn,user_notion_page_types,selected_page_type,notion_settings_status,refresh_notion_settings_btn,notion_page_max_depth],show_progress='minimal')
- public_workspace_checkbox2.change(
- fn=lambda public_option_, conn_status_: update_notion_settings(
- public_option_, conn_status_, notiongen.label),
- inputs=[public_workspace_checkbox2,notion_settings_status2],
- outputs=[user_notion_access_token2,user_notion_page_id2,to_notion_btn2,user_notion_page_types2,selected_page_type2,notion_settings_status2,refresh_notion_settings_btn2,notion_page_max_depth2],show_progress='minimal')
-
- def update_page_type(selected_page_id,page_types,curr_page_type):
- for page_type in page_types[0]:
- if page_type[0] == selected_page_id:
- return page_type[1]
- return curr_page_type
- user_notion_page_id.select(update_page_type,
- [user_notion_page_id,user_notion_page_types,selected_page_type],[selected_page_type])
- user_notion_page_id2.select(update_page_type,
- [user_notion_page_id2,user_notion_page_types2,selected_page_type2],[selected_page_type2])
-
gr.Markdown("""
""")
tab_id_state = gr.Markdown(label="Last Used Tab",value=None,elem_classes='center_text')
- gr.Markdown("""`Note: We don't store any user information. If you are hesitant to try tools of f0, reach out to us to know more.`""", elem_classes="center_text")
+ gr.Markdown("""`Note: If you have any feedback, concern or appreciation, don't be a stranger and ping us.`""", elem_classes="center_text")
gr.Markdown("""#### 💌 Built by [finding0](https://www.linkedin.com/company/finding0)""", elem_classes="center_text")
def load_usage_limits():
@@ -1736,7 +1113,7 @@ with gr.Blocks(
main_app.load(load_usage_limits,None,[user_limits,user_limits1,user_limits2])
def load_notiongen():
- data, count = check_data(column="*",table="models",all=True)
+ data = checkDB_api(column="*",table="models",all=True)
_communities = {}
for _i, _m in enumerate(data):
if not _communities.get(_m.get('community')):
@@ -1758,7 +1135,7 @@ with gr.Blocks(
_notiongen_pages_till_now = f"""NotionGen Pages: {_notiongen_pages_till_now}"""
return gr.JSON(_communities), gr.Dropdown(choices=_llm_clients,value=_def_llm_client), gr.Dropdown(choices=_models,value=_def_model), gr.JSON(_all_queries), gr.Dropdown(choices=_all_descriptions,value=_all_descriptions[0][1]), gr.Markdown(value=_notiongen_pages_till_now)
main_app.load(load_notiongen,None,[models_lib,llm_client,model,samples_lib,sample_descriptions,notiongen_pages_counter])
-
+
def update_notiongen_prompt(selected_description,samples_lib):
# samples_lib[selected_description]
if selected_description:
@@ -1775,11 +1152,127 @@ with gr.Blocks(
return gr.Dropdown(choices=_models,value=_def_model)
llm_client.change(update_models,[llm_client,models_lib],model)
- def dev_mode_activate(dev_mode):
- if dev_mode:
- return gr.Checkbox(visible=True), gr.Checkbox(visible=True), gr.DataFrame(visible=True)
- return force_json,auto_restart,additional_inputs
- dev_mode.change(dev_mode_activate,dev_mode,[force_json,auto_restart,additional_inputs])
+ def update_autosend(token):
+ if not token:
+ return gr.Checkbox(value=False,interactive=False,info="Connect your Notion or use public workspace")
+ return gr.Checkbox(interactive=True,info="Select Notion page or use public workspace")
+ user_notion_access_token2.change(update_autosend,[user_notion_access_token2],autosend_to_notion)
+
+ def refresh_notion_conn_activate():
+ return gr.Button(interactive=True)
+ connect_to_notion2.click(refresh_notion_conn_activate,None,refresh_notion_conn_btn)
+
+ def update_page_type(selected_page_id,page_types,curr_page_type):
+ for page_type in page_types[0]:
+ if page_type[0] == selected_page_id:
+ return page_type[1]
+ return curr_page_type
+ user_notion_page_id.select(update_page_type,
+ [user_notion_page_id,user_notion_page_types,selected_page_type],[selected_page_type])
+ user_notion_page_id2.select(update_page_type,
+ [user_notion_page_id2,user_notion_page_types2,selected_page_type2],[selected_page_type2])
+
+ def set_notion_settings(refresh,max_depth,curr_page_type,tab_name):
+ token_option, page_id_option, page_types = get_connected_notion_info(refresh,max_depth=max_depth)
+ if token_option:
+ token = token_option[0][1]
+ page_id = None
+ page_type = None
+ conn_status = notion_settings_choices[0]
+ if page_id_option:
+ to_notion_btn_val = "Send to My Notion 🟢"
+ page_id = page_id_option[1][1]
+ page_types = [page_types]
+ page_type = update_page_type(page_id,page_types,curr_page_type)
+ else:
+ to_notion_btn_val = "Send to Notion 🟠"
+ conn_status = notion_settings_choices[1]
+ return gr.Button(value="Reconnect 🟠"), gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.Checkbox(value=False), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Markdown(conn_status)
+ else:
+ if 'notiongen' in tab_name.lower():
+ return connect_to_notion2, user_notion_access_token2, user_notion_page_id2, to_notion_btn2, gr.Checkbox(value=True), user_notion_page_types2, selected_page_type2, notion_settings_status2
+ if 'email0' in tab_name.lower():
+ return connect_to_notion, user_notion_access_token, user_notion_page_id, to_notion_btn, gr.Checkbox(value=False), user_notion_page_types, selected_page_type, notion_settings_status
+ return connect_to_notion2, user_notion_access_token2, user_notion_page_id2, to_notion_btn2, gr.Checkbox(value=False), user_notion_page_types2, selected_page_type2, notion_settings_status2
+ def load_notion_settings(max_depth,curr_page_type,tab_name):
+ return set_notion_settings(False,max_depth,curr_page_type,tab_name)
+ main_app.load(
+ fn=lambda _max_depth, _curr_page_type :load_notion_settings(
+ _max_depth, _curr_page_type, notiongen.label),
+ inputs=[notion_page_max_depth2,selected_page_type2],
+ outputs=[connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status2],
+ show_progress='minimal')
+ main_app.load(
+ fn=lambda _max_depth, _curr_page_type :load_notion_settings(
+ _max_depth, _curr_page_type, email0.label),
+ inputs=[notion_page_max_depth,selected_page_type],
+ outputs=[connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,notion_settings_status],
+ show_progress='minimal')
+ def refresh_notion_settings(max_depth,curr_page_type,tab_name):
+ return set_notion_settings(True,max_depth,curr_page_type,tab_name)
+ refresh_notion_settings_btn2.click(
+ fn=lambda _max_depth, _curr_page_type :refresh_notion_settings(
+ _max_depth, _curr_page_type, notiongen.label),
+ inputs=[notion_page_max_depth2,selected_page_type2],
+ outputs=[connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status2])
+ refresh_notion_conn_btn.click(
+ fn=lambda _max_depth, _curr_page_type :refresh_notion_settings(
+ _max_depth, _curr_page_type, notiongen.label),
+ inputs=[notion_page_max_depth2,selected_page_type2],
+ outputs=[connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status2])
+ refresh_notion_settings_btn.click(
+ fn=lambda _max_depth, _curr_page_type :refresh_notion_settings(
+ _max_depth, _curr_page_type, notiongen.label),
+ inputs=[notion_page_max_depth,selected_page_type],
+ outputs=[connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,notion_settings_status])
+
+ def update_notion_settings(selected_public_workspace,curr_page_type,max_depth,tab_name):
+ if selected_public_workspace:
+ if type(tab_name) == str:
+ if 'notiongen' in tab_name.lower():
+ _public_page_type = 'database'
+ return gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_KEY)], value=PUBLIC_NOTION_KEY, interactive=False), gr.Dropdown(choices=[('Use Public Workspace',NOTIONGEN_PUBLIC_PAGE_ID)], value=NOTIONGEN_PUBLIC_PAGE_ID, interactive=False), gr.Button(value="Send to Public Notion 🟢"), gr.List(value=[[('Use Public Workspace',_public_page_type)]]), gr.Dropdown(value=_public_page_type), gr.Markdown(notion_settings_choices[3]), gr.Button(visible=False), gr.Slider(visible=False)
+ if 'email0' in tab_name.lower():
+ _public_page_type = 'database'
+ return gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_KEY)], value=PUBLIC_NOTION_KEY, interactive=False), gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_PAGE_ID)], value=PUBLIC_NOTION_PAGE_ID, interactive=False), gr.Button(value="Send to Public Notion 🟢"), gr.List(value=[[('Use Public Workspace',_public_page_type)]]), gr.Dropdown(value=_public_page_type), gr.Markdown(notion_settings_choices[3]), gr.Button(visible=False), gr.Slider(visible=False)
+ else:
+ token_option, page_id_option, page_types = get_connected_notion_info(max_depth=max_depth)
+ if token_option:
+ token = token_option[0][1]
+ page_id = None
+ page_type = None
+ conn_status = notion_settings_choices[0]
+ if page_id_option:
+ to_notion_btn_val = "Send to My Notion 🟢"
+ page_id = page_id_option[1][1]
+ page_types = [page_types]
+ page_type = update_page_type(page_id,page_types,curr_page_type)
+ else:
+ to_notion_btn_val = "Send to Notion 🟠"
+ conn_status = notion_settings_choices[1]
+ return gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Markdown(conn_status), gr.Button(interactive=True, visible=True), gr.Slider(visible=True, value=max_depth)
+ if type(tab_name) == str:
+ if 'notiongen' in tab_name.lower():
+ return user_notion_access_token2, user_notion_page_id2, to_notion_btn2, user_notion_page_types2, selected_page_type2, notion_settings_status2, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
+ if 'email0' in tab_name.lower():
+ return user_notion_access_token, user_notion_page_id, to_notion_btn, user_notion_page_types, selected_page_type, notion_settings_status, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
+ return user_notion_access_token2, user_notion_page_id2, to_notion_btn2, user_notion_page_types2, selected_page_type2, notion_settings_status2, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
+ public_workspace_checkbox2.change(
+ fn=lambda public_option_, page_type_, max_depth_: update_notion_settings(
+ public_option_, page_type_, max_depth_, notiongen.label),
+ inputs=[public_workspace_checkbox2,selected_page_type2,notion_page_max_depth2],
+ outputs=[user_notion_access_token2,user_notion_page_id2,to_notion_btn2,user_notion_page_types2,selected_page_type2,notion_settings_status2,refresh_notion_settings_btn2,notion_page_max_depth2],show_progress='minimal')
+ public_workspace_checkbox.change(
+ fn=lambda public_option_, page_type_, max_depth_: update_notion_settings(
+ public_option_, page_type_, max_depth_, email0.label),
+ inputs=[public_workspace_checkbox,selected_page_type,notion_page_max_depth],
+ outputs=[user_notion_access_token,user_notion_page_id,to_notion_btn,user_notion_page_types,selected_page_type,notion_settings_status,refresh_notion_settings_btn,notion_page_max_depth],show_progress='minimal')
+
+ # def dev_mode_activate(dev_mode):
+ # if dev_mode:
+ # return gr.Checkbox(visible=True), gr.DataFrame(visible=True)
+ # return force_json,additional_inputs
+ # dev_mode.change(dev_mode_activate,dev_mode,[force_json,additional_inputs])
def update_tab_id(tab_id):
return f"{tab_id}"
@@ -1791,8 +1284,8 @@ with gr.Blocks(
fn=lambda: update_tab_id(email0.id),
inputs=[],
outputs=[tab_id_state])
-
- def private_api_wrapper(description, llm_client, model, temperature, top_p, autosend_to_notion, additional_inputs, selected_page_type2, tab_id_state, force_json, use_default_env_vars, auto_restart, dev_mode, models_lib):
+
+ def notiongen_api_wrapper(description, llm_client, model, temperature, top_p, autosend_to_notion, user_notion_page_id2, selected_page_type2, user_notion_access_token2, dev_mode, additional_inputs, models_lib):
_models = models_lib.get(llm_client).get('models')
_matched_model = None
for _m in _models:
@@ -1801,223 +1294,159 @@ with gr.Blocks(
break
model = _matched_model[1]
llm_client = models_lib.get(llm_client).get('llm_source')
- print(llm_client,model)
- for _status, _notion_link, _notion_json in private_api(description, llm_client, model, temperature, top_p, autosend_to_notion, additional_inputs, selected_page_type2, tab_id_state, force_json, use_default_env_vars, auto_restart, dev_mode):
+ for _status, _notion_link, _notion_json in notiongen_api(description, llm_client, model, temperature, top_p, autosend_to_notion, user_notion_page_id2, selected_page_type2, user_notion_access_token2, dev_mode, additional_inputs):
yield _status, _notion_link, _notion_json
submit_btn.click(
- fn=private_api_wrapper,
- inputs=[description, llm_client, model, temperature, top_p, autosend_to_notion, additional_inputs, selected_page_type2, tab_id_state, force_json, use_default_env_vars, auto_restart, dev_mode, models_lib],
+ fn=notiongen_api_wrapper,
+ inputs=[description, llm_client, model, temperature, top_p, autosend_to_notion, user_notion_page_id2, selected_page_type2, user_notion_access_token2, dev_mode, additional_inputs, models_lib],
outputs=[status_output, html_output, notionJSON_output])
+ def send_to_notion_wrapper(_notion_json, _notion_access_token, _notion_page_id, _notion_page_type, _def_page_link, _public_workspace):
+ for _gen_page_link, _progress_update in send_to_notion(
+ notion_json=_notion_json,notion_key=_notion_access_token,
+ notion_page_id=_notion_page_id,notion_page_type=_notion_page_type,
+ error_page_link=_def_page_link,public_workspace=_public_workspace,
+ _action_id="notiongen_send_to_notion"):
+ yield _gen_page_link, _progress_update
+ to_notion_btn2.click(
+ fn=send_to_notion_wrapper,
+ inputs=[notionJSON_output,user_notion_access_token2,user_notion_page_id2,selected_page_type2,notiongen_page_link,gr.Text(value=NOTIONGEN_PUBLIC_PAGE_ID,visible=False)],
+ outputs=[notiongen_page_link,to_notion_update2])
+
def load_demo_view():
- _username = SESSION_DATA.get('user',{}).get('username',None)
_name = SESSION_DATA.get('user',{}).get('name',None)
_email = SESSION_DATA.get('user',{}).get('email',None)
+ _username = SESSION_DATA.get('user',{}).get('username',None)
if (_username == DEMO_USERNAME) and (not _email) and (not _name):
- return gr.TabItem(interactive=False), gr.Button(interactive=False)
- return gr.TabItem(interactive=True), gr.Button(interactive=True)
+ return gr.TabItem(interactive=False), gr.Button(interactive=False), gr.Button(interactive=False)
+ return gr.TabItem(interactive=True), gr.Button(interactive=True), gr.Button(interactive=True)
main_app.load(
fn=load_demo_view,
inputs=None,
- outputs=[email0,connect_to_notion2])
-# main_app.queue(max_size=5)
-
-
-# API PAGES (GRADIO)
-with gr.Blocks() as api_page:
- with gr.Tabs() as tabs:
- with gr.TabItem(label="APIs", id=0, interactive=False) as gr_apis:
- def google_auth_api(access_token_json: str, user_json: str, scope: str, session_data_json: json):
- access_token = json.loads(access_token_json)
- user = json.loads(user_json)
- session_data = json.loads(session_data_json)
- result = google_auth_db_sync(access_token, user, scope, session_data)
- return result
- googleAuth_api = gr.Interface(
- fn=google_auth_api,
- inputs=["text", "text", "text", "json"], # JSON strings for access_token and user
- outputs="json")
-
- def check_with_db_api(row_id_value: str, column: str, table: str, row_id_type: str, null_check: bool, all: bool):
- data, count = check_data(row_id_value, column, table, row_id_type, null_check, all)
- return data
- checkDB_api = gr.Interface(
- fn=check_with_db_api,
- inputs=["text", "text", "text", "text",
- gr.Checkbox(label="Null Check for Row ID", value=False),
- gr.Checkbox(label="All Rows", value=False)], # Inputs for email, column, table, and row_id_type
- outputs="json")
-
- def check_user_api(row_id_value: str, row_id_type: str):
- data, count = check_user(row_id_value, type=row_id_type)
- return data
- checkUser_api = gr.Interface(
- fn=check_user_api,
- inputs=["text", "text"], # Inputs for email & row_id_type
- outputs="json")
-
- def sync_notion_pages_api(row_id_value:str,row_id_type:str,refresh:bool,max_depth:int):
- return parse_user_pages(row_id_value,user_type=row_id_type,refresh=refresh,max_depth=max_depth)
- syncNotion_api = gr.Interface(
- fn=sync_notion_pages_api,
- inputs=["text","text",
- gr.Checkbox(label="Refresh", value=False),
- gr.Number(label="Max Depth", value=2, step=1)],
- outputs="json")
-
- def update_db_api(row_id_value:str,update_data_json:json,table:str,row_id_type:str,column:str):
- data_to_update = json.loads(update_data_json)
- data, count = update_data(row_id=row_id_value,data=data_to_update,table=table,row_id_type=row_id_type,column=column)
- return data
- updateDB_api = gr.Interface(
- fn=update_db_api,
- inputs=["text","json","text","text","text"],
- outputs="json")
-
- def notion_auth_api(access_code:str,redirect_uri:str,session_data_json:json):
- session_data = json.loads(session_data_json)
- notion_auth_db_sync(access_code,redirect_uri,session_data)
- return None
- notionAuth_api = gr.Interface(
- fn=notion_auth_api,
- inputs=["text","text","json"],
- outputs=None)
-
- def create_notionPage_api(parent_page_id:str, page_title:str, icon:str, properties_json:json, notion_access_token:str, parent_page_type:str):
- try:
- properties = json.loads(properties_json)
- new_page = create_page(parent_id=parent_page_id, title=page_title, icon=icon, properties=properties, cover_image=True, notion_key=notion_access_token, parent_type=parent_page_type)
- return new_page
- except Exception as e:
- print(str(e))
- return {"Error": str(e)}
- createNotionPage_api = gr.Interface(
- fn=create_notionPage_api,
- inputs=["text","text","text","json","text","text"],
- outputs="json")
-
- def update_notionPage_api(parent_id:str, block_json:json, notion_access_token:str, parent_block_type:str):
- try:
- block_json = json.loads(block_json)
- process_blueprint(parent_id=parent_id, block_json=block_json, notion_key=notion_access_token, parent_type=parent_block_type)
- return {"Success": True}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- updateNotionPage_api = gr.Interface(
- fn=update_notionPage_api,
- inputs=["text","json","text","text"],
- outputs="json")
-
- def invoke_llm_api(description:str,force_json:bool,temperature:float,top_p:float,llm:str,model:str,llm_key:str,def_env_var:bool,custom_data:str,api:bool):
- try:
- if api:
- response, chunks = invoke_llm(description,force_json,temperature,top_p,llm,model,llm_key,def_env_var,custom_data,api=api)
- return chunks
- else:
- response = invoke_llm(description,force_json,temperature,top_p,llm,model,llm_key,def_env_var,custom_data,api=api)
- return response
- except Exception as e:
- print(str(e))
- return {"Error": str(e)}
- invokeLLM_api = gr.Interface(
- fn=invoke_llm_api,
- inputs=["text",gr.Checkbox(),gr.Number(),gr.Number(),"text","text","text",gr.Checkbox(),"text",gr.Checkbox()],
- outputs="json")
+ outputs=[email0,connect_to_notion2,refresh_notion_conn_btn])
+
+ def change_labels():
+ fetched_labels = get_label_info()
+ if isinstance(fetched_labels,dict) and fetched_labels.get('data') and not all(all(item == '' for item in sublist) for sublist in fetched_labels.get('data', [])):
+ _labels = fetched_labels.get('data')
+ new_labels = [(label[1],label[0]) for label in _labels]
+ default_label = new_labels[3][0]
+ default_label_id = new_labels[3][1]
+ def_label_max_emails = [label[3] for label in _labels if label[0] == default_label_id][0]
+ step = def_label_max_emails/20
+ value = int(step*2)
+ return fetched_labels, gr.Dropdown(choices=new_labels, value=default_label), gr.Slider(maximum=def_label_max_emails, value=value, step=step, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{def_label_max_emails}'"), gr.Checkbox(value=False), gr.Button(value="Refresh Label Summary"), gr.Markdown(value=None), gr.Button(variant='secondary',visible=True)
+ else:
+ return gr.DataFrame(value=LABEL_DB.values.tolist()), gr.Dropdown(value='CATEGORY_PROMOTIONS'), gr.Slider(value=10), gr.Checkbox(value=False), gr.Button(value="Fetch Label Summary"), gr.Markdown(visible=True,value="🔴 Please connect to Gmail to fetch label summary"), gr.Button(variant='primary',visible=True)
+ main_app.load(change_labels,None,
+ [labels,labels_choices,max_emails_slider,create_csv_checkbox,get_labels_btn,get_labels_update,gmail_authenticate_btn])
+ get_labels_btn.click(change_labels,None,
+ [labels,labels_choices,max_emails_slider,create_csv_checkbox,get_labels_btn,get_labels_update,gmail_authenticate_btn])
- def get_labels_api(userinfo_json:json):
- userinfo = json.loads(userinfo_json)
- return get_labels(userinfo=userinfo)
- getLabels_api = gr.Interface(
- fn=get_labels_api,
- inputs="json",
- outputs=gr.DataFrame())
-
- def add_session_api(curr_user_id:str, id_type:str, session_json:json):
- try:
- session = json.loads(session_json)
- session_data = add_session(curr_user_id, id_type, session)
- return {"Success": True, "session_data": session_data}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- addSession_api = gr.Interface(
- fn=add_session_api,
- inputs=["text", "text", "json"],
- outputs="json")
+ def update_max_emails(labels,labels_choices,def_max,evt:gr.SelectData):
+ try:
+ def_label_max_emails = [label[3] for label in labels if label[0] == labels_choices][0]
+ except:
+ def_label_max_emails = -1
+ if def_label_max_emails >= 0:
+ step = def_label_max_emails/20
+ value = int(step*2)
+ if type(def_label_max_emails) == int:
+ return gr.Slider(maximum=def_label_max_emails, value=value, step=step, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{def_label_max_emails}'"), gr.Checkbox(value=False)
+ else:
+ return gr.Slider(maximum=def_max), gr.Checkbox(value=False)
+ labels_choices.select(update_max_emails,
+ [labels,labels_choices,max_emails],[max_emails_slider,create_csv_checkbox])
+
+ def update_labels(labels,labels_choices,max_emails,evt:gr.SelectData):
+ labels_choices = labels[evt.index[0]][evt.index[1]]
+ max_emails, csv_checkbox = update_max_emails(labels,labels_choices,max_emails,evt)
+ return labels_choices, max_emails, csv_checkbox
+ labels.select(update_labels,[labels, labels_choices, max_emails],
+ [labels_choices,max_emails_slider,create_csv_checkbox])
+
+ def analyze_btn_deactivate():
+ return gr.Button(interactive=False)
+ get_labels_btn.click(analyze_btn_deactivate,None,analyze_btn)
+
+ def analyze_btn_activate():
+ return gr.Button(interactive=True)
+ labels.change(analyze_btn_activate,None,analyze_btn)
+
+ downloadable_file_paths = gr.DataFrame(label="Files Created for the Last Analysis",value=[FILE_PATHS],type='array',col_count=(len(FILE_PATHS),'fixed'),row_count=(1,'dynamic'),interactive=False,height=216,visible=False)
+ analyze_btn.click(get_unread_emails,
+ [labels_choices, max_emails_slider, create_csv_checkbox],[update, downloadable_file_paths, analysis, domain_analysis, sample_emails, unsub_links, error_emails])
+
+ selected_csv_option = gr.Checkbox(value=False,visible=False)
+ def last_csv_option(selected_option):
+ return gr.Checkbox(value=selected_option)
+ analyze_btn.click(last_csv_option,create_csv_checkbox,selected_csv_option)
+
+ def download_links_update(downloadable_file_paths):
+ return gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][5],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][1],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][0],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][2],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][3],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][4],interactive=True)
+ downloadable_file_paths.change(download_links_update,downloadable_file_paths,
+ [download_btn,domain_analysis_download_btn,sender_analysis_download_btn,emails_download_btn,unsub_links_download_btn,email_processing_errors_download_btn])
- def delete_user_api(curr_user_id:str, id_type:str, session_data_json:json):
- try:
- session_data = json.loads(session_data_json)
- delete_user(curr_user_id,id_type,session_data)
- return {"Success": True}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- deleteUser_api = gr.Interface(
- fn=delete_user_api,
- inputs=["text", "text", "json"],
- outputs="json")
-
- def insert_data_api(table:str,data_json:json):
- try:
- data = json.loads(data_json)
- insert_data(data,table)
- return {"Success": True}
- except Exception as e:
- print(str(e))
- return {"Success": False, "Error": str(e)}
- insertDB_api = gr.Interface(
- fn=insert_data_api,
- inputs=["text","json"],
- outputs="json")
-app = gr.mount_gradio_app(app, api_page, path=API_URL)
-
-app = gr.mount_gradio_app(app, main_app, path=APP_URL, auth_dependency=get_user)
+ def reconnect_to_gmail(analyze_status):
+ if isinstance(analyze_status,str) and 'no connection with gmailapi' in analyze_status.lower():
+ return gr.Button(variant='primary',visible=True)
+ else:
+ return gr.Button(variant='secondary',visible=True)
+ update.change(reconnect_to_gmail,update,gmail_authenticate_btn)
+
+ def delete(file,sample_file,analysis_status,selected_csv_option):
+ file_to_delete = os.path.basename(file)
+ if 'Gmail0_SAMPLE' not in file_to_delete and selected_csv_option and "or download it as csv or" in analysis_status:
+ file_to_delete = os.path.join(DATA_LOCATION, file_to_delete)
+ try:
+ if os.path.exists(file_to_delete):
+ os.remove(file_to_delete)
+ print(f"File {file_to_delete} has been deleted.")
+ label="Downloaded & Deleted! Now, clean your inbox?"
+ else:
+ label="File Not Found! Click on 'Analyse'"
+ except Exception as error:
+ print(f"""🔴 Error! {error}""")
+ label="Facing Error! Try another time"
+ else:
+ label="Tick 'Create CSV/Excel', click on 'Analyse' & wait for completion!"
+ return gr.DownloadButton(value=sample_file[0][0],label=label)
+ download_btn.click(delete,
+ [download_btn,gr.List([[FILE_PATHS[5]]],visible=False),update,selected_csv_option],download_btn)
+ domain_analysis_download_btn.click(delete,
+ [domain_analysis_download_btn,gr.List([[FILE_PATHS[1]]],visible=False),update,selected_csv_option],domain_analysis_download_btn)
+ sender_analysis_download_btn.click(delete,
+ [sender_analysis_download_btn,gr.List([[FILE_PATHS[0]]],visible=False),update,selected_csv_option],sender_analysis_download_btn)
+ emails_download_btn.click(delete,
+ [emails_download_btn,gr.List([[FILE_PATHS[2]]],visible=False),update,selected_csv_option],emails_download_btn)
+ unsub_links_download_btn.click(delete,
+ [unsub_links_download_btn,gr.List([[FILE_PATHS[3]]],visible=False),update,selected_csv_option],unsub_links_download_btn)
+ email_processing_errors_download_btn.click(delete,
+ [email_processing_errors_download_btn,gr.List([[FILE_PATHS[4]]],visible=False),update,selected_csv_option],email_processing_errors_download_btn)
+
+ def send_to_notion_deactivate():
+ return gr.Button(interactive=False)
+ analyze_btn.click(send_to_notion_deactivate,None,[to_notion_btn])
+
+ def send_to_notion_activate():
+ return gr.Button(interactive=True)
+ domain_analysis.change(
+ send_to_notion_activate,None,[to_notion_btn])
+
+ def email0_to_notion_wrapper(df1_, df2_, df3_, key_, page_id_, page_type_, def_page_link_):
+ for _gen_page_link, _progress_update in email0_to_notion([df1_, df2_, df3_], [EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_COLS, UNSUB_COLS],
+ [20, 20, 20], ['Domain-wise (Top 20) Unread Emails Analysis', 'Sender-wise (Top 20) Unread Emails Analysis', 'Unsubscribe Links (Top 20) for Unread Emails'],
+ 'Unread Emails Analysis '+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f"),
+ [key_, page_id_, page_type_], def_page_link_):
+ yield _gen_page_link, _progress_update
+ to_notion_btn.click(
+ fn=email0_to_notion_wrapper,
+ inputs=[domain_analysis, analysis, unsub_links, user_notion_access_token, user_notion_page_id, selected_page_type, email0_page_link],
+ outputs=[email0_page_link,to_notion_update])
+
+
+app = gr.mount_gradio_app(app, main_app, path=APP_URL, auth_dependency=app_auth)
app = gr.mount_gradio_app(app, main_app, path=APP_ALTERNATE_ROUTE, auth=pwd_auth)
-
if __name__ == "__main__":
- uvicorn.run(app, port=8000)
- # get_sample_queries("notiongen")
-
-
-'''
- Functionalities / TODO:
- - App authentication using Google OAuth App1
- - Read access to Gmail using Google OAuth App2
- - Fetch label-wise summary
- - Fetch unread emails for a given label
- - Extract details (Date, Sender, Subject, Snippet, Body) and provide domain-wise & sender-wise analysis along with unsubscribe emails mapped to each email
- - Send the analysis & emails to Notion by creating a subpage inside the prev connected Notion page
- - Save files locally
- - Let user download & delete the saved csv files (automatic creation of files for every analyse click)
- - Let user input whether files should be created or not (create downloadable csv files checkbox send to get_unread_emails function)
- - Let user use their own notion_api_token + page_id and send data there (TODO Validation of key & page_id format is pending!)
- - Send data to signed-in user's Notion workspaces
- - Save storage.json against the email-id in supabase https://www.gradio.app/guides/creating-a-dashboard-from-supabase-data
- - Try using App2 for app authentication as well
- - Save one consolidated csv file in addition to individual ones & let user download that
- - Map NotionGen's 'Send to Notion' button to manually send template json data to Notion again if needed.
- - Create a email/pwd login for test@f0.com with daily limit of 5 clicks on Analyse or Send to Notion or Generate buttons (add email/pwd login - gradio vs supabase vs auth0; add usage_limits column in users table)
- - TODO: Create a duplicate app with original as backend
- - TODO: Save user queries & load as examples/past queries dropdown (create a table in supabase - user_id, query, result)
- - TODO: Make a limiting view for a self-serve user with own keys
- - TODO: Send to google sheets
- - TODO: On analyse run, delete all files created 24 hrs before (of all users)
- - TODO: Let user download their access token credentials & manually input
- - TODO: Schedule monthly analyses sent directly to user's email-id & Notion workspace (optional)
- - TODO: Option to mark the messages as Read
- - TODO: Option to bulk delete the messages for a selected domain or email along with other queries
- - TODO: Add integration with Coda
-'''
-
-'''REFERENCES:
- 1. https://github.com/abhishekchhibber/Gmail-Api-through-Python
- 2. https://github.com/Charlkie/PyMail/blob/master/authentication.py
- 3. https://developers.google.com/gmail/api/reference/rest/v1/users.messages/list
- 4. https://console.cloud.google.com/apis/credentials/consent?project=third-node-425006-g7
- 5. https://github.com/aksappy/unsubscriber
- 6. https://developers.notion.com/reference/retrieve-a-database
- 7. https://supabase.com/dashboard/project
-'''
+ uvicorn.run(app, port=9000)