Tree-Diagram commited on
Commit
d8a7ff4
Β·
verified Β·
1 Parent(s): 5226cd4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -76
app.py CHANGED
@@ -1,120 +1,155 @@
1
  import gradio as gr
2
- import gspread
3
- from oauth2client.service_account import ServiceAccountCredentials
4
 
5
  # 1. CONFIGURATION - SET THESE VALUES
6
- GOOGLE_SHEET_ID = "Yhttps://docs.google.com/spreadsheets/d/1ic4J-NFI-72gMhjpf-EEmj5jFPc_2kWTTOtlMZmI0OM/edit?usp=sharing" # From your spreadsheet URL
7
- API_KEY = "AIzaSyCHQI_cHzqrDzGji87enYAa6CfyZBHUPRE" # The API key you just created
8
- SHEET_NAME = "Sheet1" # Name of the tab/worksheet
9
 
10
  def get_match(phone_number):
11
  """
12
- Looks up a phone number using the Google Sheets API.
13
  """
14
  try:
15
- # Authenticate using the API key method
16
- gc = gspread.service_account_from_dict({
17
- "type": "service_account",
18
- "project_id": "valentine-matcher",
19
- "private_key_id": "dummy",
20
- "private_key": "dummy",
21
- "client_email": "dummy@valentine-matcher.iam.gserviceaccount.com",
22
- "client_id": "dummy",
23
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
24
- "token_uri": "https://oauth2.googleapis.com/token",
25
- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
26
- "client_x509_cert_url": "dummy"
27
- })
28
-
29
- # Use API key for public sheet access
30
- gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_dict(
31
- {
32
- "type": "service_account",
33
- "project_id": "valentine-matcher",
34
- "private_key_id": "dummy",
35
- "private_key": "dummy",
36
- "client_email": "dummy@valentine-matcher.iam.gserviceaccount.com",
37
- "client_id": "dummy",
38
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
39
- "token_uri": "https://oauth2.googleapis.com/token",
40
- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
41
- "client_x509_cert_url": "dummy"
42
- },
43
- scopes=['https://www.googleapis.com/auth/spreadsheets.readonly']
44
- ))
45
-
46
- # Open the sheet using the API key method for public access
47
- sh = gc.open_by_key(GOOGLE_SHEET_ID)
48
 
49
- # For public sheets with API key, use this alternative approach
50
- import requests
51
  url = f"https://sheets.googleapis.com/v4/spreadsheets/{GOOGLE_SHEET_ID}/values/{SHEET_NAME}?key={API_KEY}"
 
 
52
  response = requests.get(url)
 
 
 
 
53
  data = response.json()
54
 
55
  if 'values' not in data:
56
- return "❌ Could not read data from the sheet. Please check the setup."
57
 
58
- values = data['values']
 
59
 
60
- # Find header row and column indices
61
- header = values[0]
62
 
63
- # Adjust these column names to match your sheet exactly
64
- try:
65
- phone_col_index = header.index("4. Phone Number") # Phone column name
66
- name_col_index = header.index("1. Full Name") # Name column name
67
- except ValueError:
68
- return "❌ Column names not found in sheet. Please check the configuration."
69
 
70
- # Look for the phone number
71
- phone_number = str(phone_number).strip()
72
- match_info = None
 
 
73
 
74
- for i, row in enumerate(values[1:]): # Skip header
75
- if i >= len(values)-1:
76
- break
77
- if len(row) > phone_col_index and str(row[phone_col_index]).strip() == phone_number:
78
- # Found the person - now find their match
79
- person_name = row[name_col_index] if len(row) > name_col_index else "Unknown"
80
-
81
- # Look for this person's name in the "Match's Name" column
82
- # You need to know which column contains the match info
83
- # This depends on how you structured your pairing sheet
84
-
85
- # If you created a separate pairing sheet with columns:
86
- # "Person's Number", "Person's Name", "Match's Number", "Match's Name"
87
- # You'll need to adjust this logic
 
 
 
 
 
 
 
88
 
89
- return f"βœ… Found: {person_name}. (Match lookup logic needs to be implemented based on your sheet structure)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- return "❌ Phone number not found. Please check and try again."
 
92
 
93
  except Exception as e:
94
- return f"An error occurred: {str(e)[:200]}"
 
 
 
 
 
 
 
95
 
96
  # 2. BUILD THE GRADIO INTERFACE
97
  with gr.Blocks(title="Find Your Secret Valentine πŸ’˜", theme=gr.themes.Soft()) as demo:
98
- gr.Markdown("# πŸ’– Find Your Secret Valentine Match")
99
- gr.Markdown("Enter the phone number you used to sign up.")
 
 
100
 
101
  with gr.Row():
102
  phone_input = gr.Textbox(
103
  label="Your Phone Number",
104
  placeholder="e.g., 0206931244",
105
- info="Enter exactly as you signed up."
106
  )
107
 
108
  submit_btn = gr.Button("Find My Match! πŸš€", variant="primary")
109
  output = gr.Markdown(label="Your Match")
110
 
 
111
  submit_btn.click(fn=get_match, inputs=phone_input, outputs=output)
112
 
 
113
  gr.Examples(
114
- examples=["0206931244", "0559722884"], # Test numbers
 
 
 
 
 
115
  inputs=phone_input,
116
- label="Try an example number"
117
  )
 
 
 
 
118
 
 
119
  if __name__ == "__main__":
120
  demo.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ import pandas as pd
4
 
5
  # 1. CONFIGURATION - SET THESE VALUES
6
+ GOOGLE_SHEET_ID = "https://docs.google.com/spreadsheets/d/1ic4J-NFI-72gMhjpf-EEmj5jFPc_2kWTTOtlMZmI0OM/edit?usp=sharing" # From your spreadsheet URL (e.g., 1xYz... from docs.google.com/spreadsheets/d/1xYz.../edit)
7
+ API_KEY = "AIzaSyCHQI_cHzqrDzGji87enYAa6CfyZBHUPRE" # Your Google Sheets API key
8
+ SHEET_NAME = "Sheet1" # Name of your pairing sheet tab/worksheet
9
 
10
  def get_match(phone_number):
11
  """
12
+ Looks up a phone number in your pairing sheet using Google Sheets API.
13
  """
14
  try:
15
+ # Clean the phone number input
16
+ phone_number = str(phone_number).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Build the API URL to get ALL data from your sheet
 
19
  url = f"https://sheets.googleapis.com/v4/spreadsheets/{GOOGLE_SHEET_ID}/values/{SHEET_NAME}?key={API_KEY}"
20
+
21
+ # Make the API request
22
  response = requests.get(url)
23
+
24
+ if response.status_code != 200:
25
+ return f"❌ Could not connect to the sheet. Error: {response.status_code}"
26
+
27
  data = response.json()
28
 
29
  if 'values' not in data:
30
+ return "❌ No data found in the sheet. Please check the sheet name and sharing settings."
31
 
32
+ # Get all rows from the sheet
33
+ all_rows = data['values']
34
 
35
+ # First row contains headers - let's find column indices
36
+ headers = all_rows[0]
37
 
38
+ # Find the column indices based on your sheet structure
39
+ # From your screenshot, your columns are:
40
+ # A: "Person's Number", B: "Person's Name", C: "Match's Number", D: "Match's Name"
 
 
 
41
 
42
+ # We'll handle it flexibly - find columns by name
43
+ person_num_col = -1
44
+ person_name_col = -1
45
+ match_num_col = -1
46
+ match_name_col = -1
47
 
48
+ for i, header in enumerate(headers):
49
+ header_lower = header.lower()
50
+ if "person's number" in header_lower or "person" in header_lower and "number" in header_lower:
51
+ person_num_col = i
52
+ elif "person's name" in header_lower or "person" in header_lower and "name" in header_lower:
53
+ person_name_col = i
54
+ elif "match's number" in header_lower or "match" in header_lower and "number" in header_lower:
55
+ match_num_col = i
56
+ elif "match's name" in header_lower or "match" in header_lower and "name" in header_lower:
57
+ match_name_col = i
58
+
59
+ # Check if we found all necessary columns
60
+ if person_num_col == -1:
61
+ return "❌ Could not find 'Person's Number' column in sheet. Please check column names."
62
+
63
+ # Search for the phone number in all rows (skip header row)
64
+ for row in all_rows[1:]:
65
+ # Make sure the row has enough columns
66
+ if len(row) > person_num_col:
67
+ # Get the phone number from this row
68
+ current_phone = str(row[person_num_col]).strip()
69
 
70
+ # Check if this is the row we're looking for
71
+ if current_phone == phone_number:
72
+ # Found the person! Now get their match details
73
+
74
+ # Get person's name if available
75
+ person_name = ""
76
+ if person_name_col != -1 and len(row) > person_name_col:
77
+ person_name = row[person_name_col]
78
+
79
+ # Get match details
80
+ match_name = ""
81
+ match_number = ""
82
+
83
+ if match_name_col != -1 and len(row) > match_name_col:
84
+ match_name = row[match_name_col]
85
+
86
+ if match_num_col != -1 and len(row) > match_num_col:
87
+ match_number = row[match_num_col]
88
+
89
+ # Format the beautiful result
90
+ result_message = f"""
91
+ πŸŽ‰ **Your Secret Valentine Match is...** πŸŽ‰
92
+
93
+ **{match_name if match_name else 'Match Found!'}**
94
+
95
+ **Contact:** {match_number if match_number else 'Number not available'}
96
+
97
+ πŸ’Œ Reach out and make their day special!
98
+
99
+ ---
100
+ *Remember, you are: {person_name if person_name else phone_number}*
101
+ """
102
+ return result_message
103
 
104
+ # If we get here, the phone number wasn't found
105
+ return "❌ Phone number not found. Please check the number and try again."
106
 
107
  except Exception as e:
108
+ # Return a user-friendly error message
109
+ error_msg = str(e)
110
+ if "404" in error_msg:
111
+ return "❌ Sheet not found. Please check your Sheet ID and API Key."
112
+ elif "403" in error_msg:
113
+ return "❌ Access denied. Please ensure your sheet is shared publicly and your API key is valid."
114
+ else:
115
+ return f"❌ An error occurred: {error_msg[:100]}..."
116
 
117
  # 2. BUILD THE GRADIO INTERFACE
118
  with gr.Blocks(title="Find Your Secret Valentine πŸ’˜", theme=gr.themes.Soft()) as demo:
119
+ gr.Markdown("""
120
+ # πŸ’– Find Your Secret Valentine Match
121
+ Enter the phone number you used to sign up (exactly as you registered).
122
+ """)
123
 
124
  with gr.Row():
125
  phone_input = gr.Textbox(
126
  label="Your Phone Number",
127
  placeholder="e.g., 0206931244",
128
+ info="Enter your number exactly as it appears in the sheet."
129
  )
130
 
131
  submit_btn = gr.Button("Find My Match! πŸš€", variant="primary")
132
  output = gr.Markdown(label="Your Match")
133
 
134
+ # Connect the button to our function
135
  submit_btn.click(fn=get_match, inputs=phone_input, outputs=output)
136
 
137
+ # Add examples from your sheet for testing
138
  gr.Examples(
139
+ examples=[
140
+ ["0206931244"], # Mildred Opare
141
+ ["0559722884"], # Frankie
142
+ ["0249838187"], # Nyako Eunice Angmorkwor
143
+ ["0550203292"] # Josephine Asamoah
144
+ ],
145
  inputs=phone_input,
146
+ label="Try these test numbers from your sheet"
147
  )
148
+
149
+ # Add a footer
150
+ gr.Markdown("---")
151
+ gr.Markdown("*If you encounter any issues, please contact the organizers.*")
152
 
153
+ # Launch the app
154
  if __name__ == "__main__":
155
  demo.launch()