paila / app.py
p3rc03's picture
Update app.py
c2bae7a verified
import os
import json
import gradio as gr
from PyPDF2 import PdfReader
import requests
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# -----------------------------
# πŸ”Ή Environment Configurations
# -----------------------------
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "your_openrouter_api_key")
GOOGLE_CREDS_JSON = os.getenv("GOOGLE_CREDENTIALS_JSON", """
{
"installed": {
"client_id": "77959826351-0ksoet0t7q0hqrfv7juncs62a8h4dumq.apps.googleusercontent.com",
"project_id": "paila-475804",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "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"
}
}
""")
# -----------------------------
# πŸ”Ή OpenRouter AI Query
# -----------------------------
def query_openrouter(prompt):
try:
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json",
},
json={
"model": "mistralai/mixtral-8x7b",
"messages": [{"role": "user", "content": prompt}],
},
timeout=60,
)
data = response.json()
return data["choices"][0]["message"]["content"]
except Exception as e:
return f"❌ Error querying OpenRouter: {e}"
# -----------------------------
# πŸ”Ή File Reader (PDF/Text)
# -----------------------------
def read_file(file):
if file is None:
return "No file uploaded."
try:
if file.name.endswith(".pdf"):
reader = PdfReader(file.name)
text = "".join(page.extract_text() for page in reader.pages)
else:
text = file.read().decode("utf-8")
return text[:3000]
except Exception as e:
return f"❌ Error reading file: {e}"
# -----------------------------
# πŸ”Ή Google OAuth Headless Flow
# -----------------------------
SCOPES = [
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/documents.readonly",
"https://www.googleapis.com/auth/gmail.readonly",
]
def google_connect():
try:
creds_data = json.loads(GOOGLE_CREDS_JSON)
flow = InstalledAppFlow.from_client_config(creds_data, SCOPES)
# Generate manual verification URL
auth_url, _ = flow.authorization_url(prompt="consent", access_type="offline", include_granted_scopes="true")
return f"πŸ”— Visit this link to authorize:\n\n{auth_url}\n\nThen copy and paste the **authorization code** below."
except Exception as e:
return f"❌ Error generating Google auth URL: {e}"
def google_authenticate(auth_code):
try:
creds_data = json.loads(GOOGLE_CREDS_JSON)
flow = InstalledAppFlow.from_client_config(creds_data, SCOPES)
flow.fetch_token(code=auth_code)
creds = flow.credentials
# Test Google Drive connection
drive_service = build("drive", "v3", credentials=creds)
gmail_service = build("gmail", "v1", credentials=creds)
files = drive_service.files().list(pageSize=5, fields="files(id, name)").execute().get("files", [])
unread = gmail_service.users().messages().list(userId="me", q="is:unread").execute().get("messages", [])
return (
"βœ… Connected successfully!\n\n"
f"πŸ“ Drive Files: {[f['name'] for f in files]}\n"
f"πŸ“¬ Unread Emails: {len(unread)}"
)
except Exception as e:
return f"❌ Authentication failed: {e}"
# -----------------------------
# πŸ”Ή AI Chat Logic
# -----------------------------
def chat_with_ai(prompt, file):
file_text = read_file(file)
context = f"File Content:\n{file_text}\n\nUser Prompt:\n{prompt}"
return query_openrouter(context)
def clear_fields():
return "", None, "", "", ""
# -----------------------------
# πŸ”Ή Gradio Interface
# -----------------------------
with gr.Blocks(title="Paila AI + Google Integration") as app:
gr.Markdown("## πŸ€– Paila AI β€” Google Drive, Docs, Sheets & Gmail Integration")
with gr.Tab("πŸ’¬ Chat"):
user_input = gr.Textbox(label="Enter your prompt")
file_input = gr.File(label="Upload PDF/Text (optional)")
output = gr.Textbox(label="AI Response")
submit = gr.Button("πŸš€ Run")
clear_btn = gr.Button("🧹 Clear")
submit.click(chat_with_ai, inputs=[user_input, file_input], outputs=output)
clear_btn.click(clear_fields, outputs=[user_input, file_input, output])
with gr.Tab("πŸ” Google Connect"):
with gr.Row():
connect_btn = gr.Button("πŸ”— Generate Google Auth Link")
connect_output = gr.Textbox(label="Step 1: Authorization Link")
connect_btn.click(google_connect, outputs=connect_output)
with gr.Row():
auth_code_input = gr.Textbox(label="Step 2: Paste Authorization Code")
auth_btn = gr.Button("βœ… Verify & Connect")
auth_output = gr.Textbox(label="Connection Result")
auth_btn.click(google_authenticate, inputs=auth_code_input, outputs=auth_output)
app.launch(server_name="0.0.0.0", server_port=7860)