p3rc03 commited on
Commit
c2bae7a
Β·
verified Β·
1 Parent(s): 12d70b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -48
app.py CHANGED
@@ -3,29 +3,30 @@ import json
3
  import gradio as gr
4
  from PyPDF2 import PdfReader
5
  import requests
6
- from googleapiclient.discovery import build
7
  from google_auth_oauthlib.flow import InstalledAppFlow
 
8
 
9
  # -----------------------------
10
  # πŸ”Ή Environment Configurations
11
  # -----------------------------
12
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "your_openrouter_api_key")
 
13
  GOOGLE_CREDS_JSON = os.getenv("GOOGLE_CREDENTIALS_JSON", """
14
  {
15
- "web": {
16
  "client_id": "77959826351-0ksoet0t7q0hqrfv7juncs62a8h4dumq.apps.googleusercontent.com",
17
  "project_id": "paila-475804",
18
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
19
  "token_uri": "https://oauth2.googleapis.com/token",
20
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
21
- "client_secret": "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",
22
- "redirect_uris": ["https://huggingface.co/spaces/p3rc03/paila"]
23
  }
24
  }
25
  """)
26
 
27
  # -----------------------------
28
- # πŸ”Ή AI Response (OpenRouter)
29
  # -----------------------------
30
  def query_openrouter(prompt):
31
  try:
@@ -58,70 +59,55 @@ def read_file(file):
58
  text = "".join(page.extract_text() for page in reader.pages)
59
  else:
60
  text = file.read().decode("utf-8")
61
- return text[:3000] # Keep light
62
  except Exception as e:
63
  return f"❌ Error reading file: {e}"
64
 
65
  # -----------------------------
66
- # πŸ”Ή Headless Google OAuth
67
  # -----------------------------
 
 
 
 
 
 
 
68
  def google_connect():
69
  try:
70
  creds_data = json.loads(GOOGLE_CREDS_JSON)
71
- flow = InstalledAppFlow.from_client_config(
72
- creds_data,
73
- scopes=[
74
- "https://www.googleapis.com/auth/drive.metadata.readonly",
75
- "https://www.googleapis.com/auth/spreadsheets.readonly",
76
- "https://www.googleapis.com/auth/documents.readonly",
77
- "https://www.googleapis.com/auth/gmail.readonly",
78
- ],
79
- )
80
- auth_url, _ = flow.authorization_url(prompt="consent")
81
- return f"πŸ”— Visit this URL to authorize access:\n\n{auth_url}\n\nThen paste the **authorization code** below."
82
  except Exception as e:
83
- return f"❌ Error generating Google auth link: {e}"
84
 
85
  def google_authenticate(auth_code):
86
  try:
87
  creds_data = json.loads(GOOGLE_CREDS_JSON)
88
- flow = InstalledAppFlow.from_client_config(
89
- creds_data,
90
- scopes=[
91
- "https://www.googleapis.com/auth/drive.metadata.readonly",
92
- "https://www.googleapis.com/auth/spreadsheets.readonly",
93
- "https://www.googleapis.com/auth/documents.readonly",
94
- "https://www.googleapis.com/auth/gmail.readonly",
95
- ],
96
- )
97
  flow.fetch_token(code=auth_code)
98
  creds = flow.credentials
99
 
100
- # Example Google integrations
101
  drive_service = build("drive", "v3", credentials=creds)
102
- sheet_service = build("sheets", "v4", credentials=creds)
103
- doc_service = build("docs", "v1", credentials=creds)
104
  gmail_service = build("gmail", "v1", credentials=creds)
105
 
106
- # Drive sample
107
- results = drive_service.files().list(pageSize=5, fields="files(id, name)").execute()
108
- drive_items = results.get("files", [])
109
-
110
- # Gmail sample (fetch unread count)
111
- gmail_results = gmail_service.users().messages().list(userId="me", labelIds=["INBOX"], q="is:unread").execute()
112
- unread_count = len(gmail_results.get("messages", [])) if gmail_results.get("messages") else 0
113
 
114
  return (
115
- f"βœ… Google Connected Successfully!\n\n"
116
- f"πŸ“ Drive Files: {[f['name'] for f in drive_items]}\n"
117
- f"πŸ“¬ Unread Emails: {unread_count}\n"
118
  )
119
-
120
  except Exception as e:
121
- return f"❌ Authentication error: {e}"
122
 
123
  # -----------------------------
124
- # πŸ”Ή AI Chat Function
125
  # -----------------------------
126
  def chat_with_ai(prompt, file):
127
  file_text = read_file(file)
@@ -132,10 +118,10 @@ def clear_fields():
132
  return "", None, "", "", ""
133
 
134
  # -----------------------------
135
- # πŸ”Ή Gradio UI
136
  # -----------------------------
137
  with gr.Blocks(title="Paila AI + Google Integration") as app:
138
- gr.Markdown("## πŸ€– Paila AI with Google Drive, Docs, Sheets, and Gmail Integration")
139
 
140
  with gr.Tab("πŸ’¬ Chat"):
141
  user_input = gr.Textbox(label="Enter your prompt")
@@ -149,14 +135,14 @@ with gr.Blocks(title="Paila AI + Google Integration") as app:
149
 
150
  with gr.Tab("πŸ” Google Connect"):
151
  with gr.Row():
152
- connect_btn = gr.Button("πŸ”— Get Google Auth Link")
153
  connect_output = gr.Textbox(label="Step 1: Authorization Link")
154
  connect_btn.click(google_connect, outputs=connect_output)
155
 
156
  with gr.Row():
157
  auth_code_input = gr.Textbox(label="Step 2: Paste Authorization Code")
158
  auth_btn = gr.Button("βœ… Verify & Connect")
159
- auth_output = gr.Textbox(label="Connection Status")
160
  auth_btn.click(google_authenticate, inputs=auth_code_input, outputs=auth_output)
161
 
162
  app.launch(server_name="0.0.0.0", server_port=7860)
 
3
  import gradio as gr
4
  from PyPDF2 import PdfReader
5
  import requests
6
+ from google.oauth2.credentials import Credentials
7
  from google_auth_oauthlib.flow import InstalledAppFlow
8
+ from googleapiclient.discovery import build
9
 
10
  # -----------------------------
11
  # πŸ”Ή Environment Configurations
12
  # -----------------------------
13
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "your_openrouter_api_key")
14
+
15
  GOOGLE_CREDS_JSON = os.getenv("GOOGLE_CREDENTIALS_JSON", """
16
  {
17
+ "installed": {
18
  "client_id": "77959826351-0ksoet0t7q0hqrfv7juncs62a8h4dumq.apps.googleusercontent.com",
19
  "project_id": "paila-475804",
20
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
21
  "token_uri": "https://oauth2.googleapis.com/token",
22
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
23
+ "client_secret": "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"
 
24
  }
25
  }
26
  """)
27
 
28
  # -----------------------------
29
+ # πŸ”Ή OpenRouter AI Query
30
  # -----------------------------
31
  def query_openrouter(prompt):
32
  try:
 
59
  text = "".join(page.extract_text() for page in reader.pages)
60
  else:
61
  text = file.read().decode("utf-8")
62
+ return text[:3000]
63
  except Exception as e:
64
  return f"❌ Error reading file: {e}"
65
 
66
  # -----------------------------
67
+ # πŸ”Ή Google OAuth Headless Flow
68
  # -----------------------------
69
+ SCOPES = [
70
+ "https://www.googleapis.com/auth/drive.metadata.readonly",
71
+ "https://www.googleapis.com/auth/spreadsheets.readonly",
72
+ "https://www.googleapis.com/auth/documents.readonly",
73
+ "https://www.googleapis.com/auth/gmail.readonly",
74
+ ]
75
+
76
  def google_connect():
77
  try:
78
  creds_data = json.loads(GOOGLE_CREDS_JSON)
79
+ flow = InstalledAppFlow.from_client_config(creds_data, SCOPES)
80
+
81
+ # Generate manual verification URL
82
+ auth_url, _ = flow.authorization_url(prompt="consent", access_type="offline", include_granted_scopes="true")
83
+ return f"πŸ”— Visit this link to authorize:\n\n{auth_url}\n\nThen copy and paste the **authorization code** below."
 
 
 
 
 
 
84
  except Exception as e:
85
+ return f"❌ Error generating Google auth URL: {e}"
86
 
87
  def google_authenticate(auth_code):
88
  try:
89
  creds_data = json.loads(GOOGLE_CREDS_JSON)
90
+ flow = InstalledAppFlow.from_client_config(creds_data, SCOPES)
 
 
 
 
 
 
 
 
91
  flow.fetch_token(code=auth_code)
92
  creds = flow.credentials
93
 
94
+ # Test Google Drive connection
95
  drive_service = build("drive", "v3", credentials=creds)
 
 
96
  gmail_service = build("gmail", "v1", credentials=creds)
97
 
98
+ files = drive_service.files().list(pageSize=5, fields="files(id, name)").execute().get("files", [])
99
+ unread = gmail_service.users().messages().list(userId="me", q="is:unread").execute().get("messages", [])
 
 
 
 
 
100
 
101
  return (
102
+ "βœ… Connected successfully!\n\n"
103
+ f"πŸ“ Drive Files: {[f['name'] for f in files]}\n"
104
+ f"πŸ“¬ Unread Emails: {len(unread)}"
105
  )
 
106
  except Exception as e:
107
+ return f"❌ Authentication failed: {e}"
108
 
109
  # -----------------------------
110
+ # πŸ”Ή AI Chat Logic
111
  # -----------------------------
112
  def chat_with_ai(prompt, file):
113
  file_text = read_file(file)
 
118
  return "", None, "", "", ""
119
 
120
  # -----------------------------
121
+ # πŸ”Ή Gradio Interface
122
  # -----------------------------
123
  with gr.Blocks(title="Paila AI + Google Integration") as app:
124
+ gr.Markdown("## πŸ€– Paila AI β€” Google Drive, Docs, Sheets & Gmail Integration")
125
 
126
  with gr.Tab("πŸ’¬ Chat"):
127
  user_input = gr.Textbox(label="Enter your prompt")
 
135
 
136
  with gr.Tab("πŸ” Google Connect"):
137
  with gr.Row():
138
+ connect_btn = gr.Button("πŸ”— Generate Google Auth Link")
139
  connect_output = gr.Textbox(label="Step 1: Authorization Link")
140
  connect_btn.click(google_connect, outputs=connect_output)
141
 
142
  with gr.Row():
143
  auth_code_input = gr.Textbox(label="Step 2: Paste Authorization Code")
144
  auth_btn = gr.Button("βœ… Verify & Connect")
145
+ auth_output = gr.Textbox(label="Connection Result")
146
  auth_btn.click(google_authenticate, inputs=auth_code_input, outputs=auth_output)
147
 
148
  app.launch(server_name="0.0.0.0", server_port=7860)