SuriRaja commited on
Commit
d35d415
·
verified ·
1 Parent(s): 6aa11d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -102
app.py CHANGED
@@ -1,22 +1,19 @@
1
  import streamlit as st
2
- import uuid
3
  import cv2
4
- import numpy as np
5
  from PIL import Image
 
6
  import tempfile
7
- import pickle
8
  import os
 
 
9
  from datetime import datetime
10
  from googleapiclient.discovery import build
11
  from googleapiclient.http import MediaFileUpload
12
  from google.auth.transport.requests import Request
13
  from simple_salesforce import Salesforce
 
14
 
15
- # === Google Drive Setup ===
16
- REG_FOLDER_ID = '1qkcR7nQTEtiMH9OFUv2bGxVn08E3dKjF' # Registered images folder
17
- INTRUDER_FOLDER_ID = '1PPAUWU-wMx7fek73p-hqPqYQypYtG8Ob' # Intruder folder
18
-
19
- # === Salesforce Setup ===
20
  sf = Salesforce(
21
  username='suriraja822@agentforce.com',
22
  password='Sati@1010',
@@ -24,112 +21,137 @@ sf = Salesforce(
24
  domain='login'
25
  )
26
 
27
- def upload_to_drive(image, filename, folder_id):
 
 
 
 
 
 
 
28
  creds = None
29
  if os.path.exists("token.pickle"):
30
  with open("token.pickle", "rb") as token:
31
  creds = pickle.load(token)
32
- if creds and creds.expired and creds.refresh_token:
33
- creds.refresh(Request())
 
34
  service = build('drive', 'v3', credentials=creds)
35
-
36
- image_pil = Image.fromarray(image)
37
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
38
- image_pil.save(temp_file.name)
39
-
40
- file_metadata = {'name': filename, 'parents': [folder_id]}
41
- media = MediaFileUpload(temp_file.name, mimetype='image/jpeg')
42
- file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
43
-
44
- file_id = file.get('id')
45
- public_link = f"https://drive.google.com/uc?id={file_id}"
46
- os.remove(temp_file.name)
47
-
48
- # Make file public
 
 
49
  try:
50
- service.permissions().create(
51
- fileId=file_id,
52
- body={'role': 'reader', 'type': 'anyone'}
53
- ).execute()
54
  except Exception as e:
55
- st.warning(f"Failed to set permission: {e}")
56
 
57
- return public_link
58
-
59
- # === Streamlit UI ===
60
- st.set_page_config(page_title="Hotel Registration", layout="wide")
61
- st.title("📸 Hotel Guest & Staff Registration")
 
62
 
63
- tab1, tab2 = st.tabs(["🛎️ Guest Registration", "👮 Staff Registration"])
 
64
 
65
- # === Guest Tab ===
66
  with tab1:
67
- st.subheader("Guest Registration")
68
-
69
- guest_name = st.text_input("Guest Name")
70
- guest_aadhar = st.text_input("Aadhar Number")
71
- guest_phone = st.text_input("Phone Number")
72
- guest_room = st.text_input("Room Number")
73
-
74
- id_photo = st.file_uploader("Upload ID Card Photo", type=["jpg", "jpeg", "png"])
75
- guest_image = st.camera_input("Capture Guest Photo")
76
-
77
- if st.button(" Register Guest"):
78
- if guest_image and id_photo and all([guest_name, guest_aadhar, guest_phone, guest_room]):
79
- guest_np = np.array(Image.open(guest_image).convert('RGB'))
80
-
81
- filename = f"G_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
82
- try:
83
- image_link = upload_to_drive(guest_np, filename, REG_FOLDER_ID)
84
- st.image(guest_np, caption="Guest Registered")
85
-
86
- result = sf.Guest__c.create({
87
- "Name": guest_name,
88
- "Aadhar_Number__c": guest_aadhar,
89
- "Phone_Number__c": guest_phone,
90
- "Room_Number__c": guest_room,
91
- "Check_In__c": datetime.utcnow().isoformat(),
92
- "Image_Link__c": image_link
93
- })
94
-
95
- st.success("🎉 Guest Registered in Salesforce!")
96
- st.json(result)
97
- except Exception as e:
98
- st.error(f"Salesforce Error: {e}")
 
 
 
 
99
  else:
100
- st.warning("📋 Please fill all fields and upload both photos.")
101
 
102
- # === Staff Tab ===
103
  with tab2:
104
- st.subheader("Staff Registration")
105
-
106
- staff_name = st.text_input("Staff Name")
107
- staff_id = st.text_input("Staff ID")
108
- staff_dept = st.selectbox("Department", ["Security", "Reception", "Housekeeping", "Maintenance", "Kitchen"])
109
-
110
- id_card = st.file_uploader("Upload ID Card (Staff)", type=["jpg", "jpeg", "png"], key="staff")
111
- staff_image = st.camera_input("Capture Staff Photo")
112
-
113
- if st.button(" Register Staff"):
114
- if staff_image and id_card and all([staff_name, staff_id, staff_dept]):
115
- staff_np = np.array(Image.open(staff_image).convert('RGB'))
116
-
117
- filename = f"S_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
118
- try:
119
- image_link = upload_to_drive(staff_np, filename, REG_FOLDER_ID)
120
- st.image(staff_np, caption="Staff Registered")
121
-
122
- result = sf.Staff__c.create({
123
- "Name": staff_name,
124
- "Staff_ID__c": staff_id,
125
- "Department__c": staff_dept,
126
- "Registered_On__c": datetime.utcnow().isoformat(),
127
- "Image_Link__c": image_link
128
- })
129
-
130
- st.success("✅ Staff Registered in Salesforce!")
131
- st.json(result)
132
- except Exception as e:
133
- st.error(f"Salesforce Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  else:
135
- st.warning("📋 Please fill all fields and upload both photos.")
 
1
  import streamlit as st
 
2
  import cv2
 
3
  from PIL import Image
4
+ import io
5
  import tempfile
 
6
  import os
7
+ import pickle
8
+ import requests
9
  from datetime import datetime
10
  from googleapiclient.discovery import build
11
  from googleapiclient.http import MediaFileUpload
12
  from google.auth.transport.requests import Request
13
  from simple_salesforce import Salesforce
14
+ import pytz
15
 
16
+ # === SALESFORCE SETUP ===
 
 
 
 
17
  sf = Salesforce(
18
  username='suriraja822@agentforce.com',
19
  password='Sati@1010',
 
21
  domain='login'
22
  )
23
 
24
+ # === CONSTANTS ===
25
+ UPLOAD_FOLDER_ID = '1qkcR7nQTEtiMH9OFUv2bGxVn08E3dKjF'
26
+
27
+ def get_vacant_rooms():
28
+ rooms = sf.query("SELECT Id, Name FROM Hotel_Room__c WHERE Room_Status__c = 'Vacant'")
29
+ return {room['Name']: room['Id'] for room in rooms['records']}
30
+
31
+ def upload_image_to_drive(image_np, filename):
32
  creds = None
33
  if os.path.exists("token.pickle"):
34
  with open("token.pickle", "rb") as token:
35
  creds = pickle.load(token)
36
+ if not creds or not creds.valid:
37
+ if creds and creds.expired and creds.refresh_token:
38
+ creds.refresh(Request())
39
  service = build('drive', 'v3', credentials=creds)
40
+ image = Image.fromarray(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB))
41
+ buf = io.BytesIO()
42
+ image.save(buf, format="JPEG")
43
+ buf.seek(0)
44
+
45
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
46
+ tmp.write(buf.read())
47
+ tmp.flush()
48
+ file_metadata = {'name': filename, 'parents': [UPLOAD_FOLDER_ID]}
49
+ media = MediaFileUpload(tmp.name, mimetype='image/jpeg')
50
+ uploaded_file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
51
+ file_id = uploaded_file.get('id')
52
+ os.remove(tmp.name)
53
+ return f"https://drive.google.com/uc?id={file_id}"
54
+
55
+ def save_guest_to_sf(data):
56
  try:
57
+ sf.Hotel_Guest__c.create(data)
58
+ st.success("✅ Guest registered successfully.")
 
 
59
  except Exception as e:
60
+ st.error(f" Salesforce Guest Error: {e}")
61
 
62
+ def save_staff_to_sf(data):
63
+ try:
64
+ sf.Hotel_Staff__c.create(data)
65
+ st.success(" Staff registered successfully.")
66
+ except Exception as e:
67
+ st.error(f"❌ Salesforce Staff Error: {e}")
68
 
69
+ st.title("🏨 Hotel Guest and Staff Registration")
70
+ tab1, tab2 = st.tabs(["👤 Guest", "👨‍💼 Staff"])
71
 
 
72
  with tab1:
73
+ st.header("Register a Guest")
74
+ fname = st.text_input("First Name")
75
+ lname = st.text_input("Last Name")
76
+ email = st.text_input("Email")
77
+ phone = st.text_input("Phone")
78
+ id_number = st.text_input("ID Number")
79
+ special_requests = st.text_area("Special Requests")
80
+ emergency_contact = st.text_input("Emergency Contact")
81
+ vacant_rooms = get_vacant_rooms()
82
+ room_name = st.selectbox("Assign Room", list(vacant_rooms.keys()))
83
+ capture = st.camera_input("Capture Guest Photo")
84
+
85
+ if st.button("📝 Register Guest"):
86
+ if capture:
87
+ timestamp = datetime.now(pytz.timezone('Asia/Kolkata')).strftime("%Y%m%d%H%M%S")
88
+ image = Image.open(capture)
89
+ image_np = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
90
+ file_name = f"G_{timestamp}.jpg"
91
+ photo_url = upload_image_to_drive(image_np, file_name)
92
+
93
+ guest_data = {
94
+ 'First_Name__c': fname,
95
+ 'Last_Name__c': lname,
96
+ 'Email__c': email,
97
+ 'Phone__c': phone,
98
+ 'ID_Number__c': id_number,
99
+ 'Special_Requests__c': special_requests,
100
+ 'Emergency_Contact__c': emergency_contact,
101
+ 'Room_Number__c': vacant_rooms[room_name],
102
+ 'Check_In_Date__c': datetime.utcnow().isoformat(),
103
+ 'Photo_Uploaded__c': photo_url,
104
+ 'HF_Registered__c': True,
105
+ 'Guest_Status__c': 'Checked In',
106
+ 'Name': f"{fname} {lname}"
107
+ }
108
+ save_guest_to_sf(guest_data)
109
  else:
110
+ st.warning("📸 Please capture a photo before registering.")
111
 
 
112
  with tab2:
113
+ st.header("Register a Staff Member")
114
+ fname = st.text_input("Staff First Name")
115
+ lname = st.text_input("Staff Last Name")
116
+ email = st.text_input("Staff Email")
117
+ phone = st.text_input("Staff Phone")
118
+ emp_number = st.text_input("Employee Number")
119
+ department = st.text_input("Department")
120
+ position = st.text_input("Position")
121
+ shift = st.selectbox("Shift", ["Morning", "Evening", "Night"])
122
+ status = st.selectbox("Status", ["Active", "Inactive"])
123
+ access = st.selectbox("Access Level", ["Low", "Medium", "High"])
124
+ badge = st.text_input("Badge Number")
125
+ supervisor = st.text_input("Supervisor")
126
+ hire_date = st.date_input("Hire Date")
127
+ capture = st.camera_input("Capture Staff Photo")
128
+
129
+ if st.button("📝 Register Staff"):
130
+ if capture:
131
+ timestamp = datetime.now(pytz.timezone('Asia/Kolkata')).strftime("%Y%m%d%H%M%S")
132
+ image = Image.open(capture)
133
+ image_np = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
134
+ file_name = f"S_{timestamp}.jpg"
135
+ photo_url = upload_image_to_drive(image_np, file_name)
136
+
137
+ staff_data = {
138
+ 'First_Name__c': fname,
139
+ 'Last_Name__c': lname,
140
+ 'Email__c': email,
141
+ 'Phone__c': phone,
142
+ 'Employee_Number__c': emp_number,
143
+ 'Department__c': department,
144
+ 'Position__c': position,
145
+ 'Shift__c': shift,
146
+ 'Employment_Status__c': status,
147
+ 'Access_Level__c': access,
148
+ 'Badge_Number__c': badge,
149
+ 'Supervisor__c': supervisor,
150
+ 'Hire_Date__c': hire_date.isoformat(),
151
+ 'Photo_Uploaded__c': photo_url,
152
+ 'HF_Registered__c': True,
153
+ 'Name': f"{fname} {lname}"
154
+ }
155
+ save_staff_to_sf(staff_data)
156
  else:
157
+ st.warning("📸 Please capture a photo before registering.")