SuriRaja commited on
Commit
4153de7
·
verified ·
1 Parent(s): 3c64d21

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -89
app.py CHANGED
@@ -1,33 +1,29 @@
1
  import streamlit as st
 
2
  import cv2
3
- import numpy as np
4
  import tempfile
5
- from PIL import Image
6
- import requests
7
- import os
8
  import pickle
9
  import io
 
 
10
  from datetime import datetime
11
- import uuid
12
  from googleapiclient.discovery import build
13
  from googleapiclient.http import MediaFileUpload
14
  from google.auth.transport.requests import Request
15
-
16
  from simple_salesforce import Salesforce
17
 
18
- # === SALESFORCE SETUP ===
19
  sf = Salesforce(
20
- username='suriraja822@agentforce.com',
21
- password='Sati@1010',
22
- security_token='B9nS0HEyBE7YmWllqXCyiOJpY',
23
- domain='login'
24
  )
25
 
26
- # === GOOGLE DRIVE SETUP ===
27
- GUEST_FOLDER_ID = '1qkcR7nQTEtiMH9OFUv2bGxVn08E3dKjF'
28
- STAFF_FOLDER_ID = '1PPAUWU-wMx7fek73p-hqPqYQypYtG8Ob'
29
 
30
- def upload_image_to_drive(image, folder_id, filename):
31
  creds = None
32
  if os.path.exists("token.pickle"):
33
  with open("token.pickle", "rb") as token:
@@ -37,92 +33,96 @@ def upload_image_to_drive(image, folder_id, filename):
37
  creds.refresh(Request())
38
  service = build('drive', 'v3', credentials=creds)
39
 
 
 
 
 
 
40
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
41
- image.save(tmp.name)
42
- file_metadata = {'name': filename, 'parents': [folder_id]}
 
43
  media = MediaFileUpload(tmp.name, mimetype='image/jpeg')
44
- uploaded = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
 
 
 
 
 
45
  os.remove(tmp.name)
46
- return f"https://drive.google.com/uc?id={uploaded.get('id')}"
47
-
48
- # === CAMERA CAPTURE ===
49
- def capture_image():
50
- cap = cv2.VideoCapture(0)
51
- st.info("📸 Press 's' to take a snapshot, then close the camera window.")
52
- img = None
53
- while True:
54
- ret, frame = cap.read()
55
- if not ret:
56
- break
57
- cv2.imshow("Press 's' to save, 'q' to quit", frame)
58
- k = cv2.waitKey(1)
59
- if k % 256 == ord('s'):
60
- img = frame
61
- break
62
- elif k % 256 == ord('q'):
63
- break
64
- cap.release()
65
- cv2.destroyAllWindows()
66
- if img is not None:
67
- return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
68
- return None
69
-
70
- # === STREAMLIT UI ===
71
- st.title("🏨 Staff & Guest Registration (With Camera & Salesforce)")
72
 
73
- tab1, tab2 = st.tabs(["🧳 Guest", "👮 Staff"])
 
 
74
 
75
  with tab1:
76
- st.header("📋 Register Guest")
77
- first_name = st.text_input("First Name")
78
- last_name = st.text_input("Last Name")
79
- room_number = st.text_input("Room Number")
80
- st.subheader("📸 Capture ID Photo")
81
- if st.button("Capture Guest ID Photo"):
82
- guest_img = capture_image()
83
- if guest_img:
84
- st.image(guest_img, caption="Captured Guest ID", width=300)
85
- filename = f"guest_{first_name}_{uuid.uuid4().hex[:6]}.jpg"
86
- img_url = upload_image_to_drive(guest_img, GUEST_FOLDER_ID, filename)
87
- st.success("✅ Uploaded to Drive")
 
 
 
88
 
89
  try:
90
- sf.Hotel_Guest__c.create({
91
- 'First_Name__c': first_name,
92
- 'Last_Name__c': last_name,
93
- 'Room_Number__c': room_number,
94
- 'HF_Registered__c': True,
95
- 'Photo_Uploaded__c': True,
96
- 'Guest_Status__c': 'Checked In',
97
- 'Check_In_Date__c': datetime.utcnow().isoformat(),
98
- })
99
- st.success("✅ Guest Registered in Salesforce")
 
 
 
 
 
 
 
 
 
100
  except Exception as e:
101
- st.error(f"❌ Salesforce Error: {e}")
 
 
102
 
103
  with tab2:
104
- st.header("📋 Register Staff")
105
- sf_first = st.text_input("First Name", key="staff_fn")
106
- sf_last = st.text_input("Last Name", key="staff_ln")
107
- sf_dept = st.selectbox("Department", ["Security", "Housekeeping", "Reception", "Engineering"])
 
108
 
109
- st.subheader("📸 Capture Staff ID Photo")
110
- if st.button("Capture Staff ID Photo"):
111
- staff_img = capture_image()
112
- if staff_img:
113
- st.image(staff_img, caption="Captured Staff ID", width=300)
114
- filename = f"staff_{sf_first}_{uuid.uuid4().hex[:6]}.jpg"
115
- img_url = upload_image_to_drive(staff_img, STAFF_FOLDER_ID, filename)
116
- st.success("✅ Uploaded to Drive")
117
 
118
  try:
119
- sf.Hotel_Staff__c.create({
120
- 'First_Name__c': sf_first,
121
- 'Last_Name__c': sf_last,
122
- 'Department__c': sf_dept,
123
- 'HF_Registered__c': True,
124
- 'Photo_Uploaded__c': True,
125
- })
126
- st.success("✅ Staff Registered in Salesforce")
127
  except Exception as e:
128
- st.error(f"❌ Salesforce Error: {e}")
 
 
 
1
  import streamlit as st
2
+ import os
3
  import cv2
 
4
  import tempfile
 
 
 
5
  import pickle
6
  import io
7
+ import numpy as np
8
+ from PIL import Image
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
+ # ==== Salesforce Login ====
16
  sf = Salesforce(
17
+ username="suriraja822@agentforce.com",
18
+ password="Sati@1010",
19
+ security_token="B9nS0HEyBE7YmWllqXCyiOJpY",
20
+ domain="login"
21
  )
22
 
23
+ # ==== Google Drive Setup ====
24
+ REG_FOLDER_ID = '1qkcR7nQTEtiMH9OFUv2bGxVn08E3dKjF'
 
25
 
26
+ def upload_image_to_drive(image_np, prefix):
27
  creds = None
28
  if os.path.exists("token.pickle"):
29
  with open("token.pickle", "rb") as token:
 
33
  creds.refresh(Request())
34
  service = build('drive', 'v3', credentials=creds)
35
 
36
+ filename = f"{prefix}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.jpg"
37
+ image_pil = Image.fromarray(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB))
38
+ buf = io.BytesIO()
39
+ image_pil.save(buf, format="JPEG")
40
+ buf.seek(0)
41
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
42
+ tmp.write(buf.read())
43
+ tmp.flush()
44
+ file_metadata = {'name': filename, 'parents': [REG_FOLDER_ID]}
45
  media = MediaFileUpload(tmp.name, mimetype='image/jpeg')
46
+ uploaded_file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
47
+ file_id = uploaded_file.get("id")
48
+ service.permissions().create(
49
+ fileId=file_id,
50
+ body={'role': 'reader', 'type': 'anyone'}
51
+ ).execute()
52
  os.remove(tmp.name)
53
+ return f"https://drive.google.com/uc?id={file_id}&export=download"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # ==== UI ====
56
+ st.title("🏨 Hotel Guest & Staff Registration")
57
+ tab1, tab2 = st.tabs(["👤 Guest Check-In", "👔 Staff Registration"])
58
 
59
  with tab1:
60
+ st.subheader("Guest Registration")
61
+ guest_name = st.text_input("Full Name")
62
+ guest_mobile = st.text_input("Mobile Number")
63
+ guest_email = st.text_input("Email")
64
+ guest_id_photo = st.file_uploader("Upload ID Proof", type=["jpg", "jpeg", "png"])
65
+ room_number = st.text_input("Assign Room Number")
66
+
67
+ guest_cam = st.camera_input("Capture Guest Photo")
68
+ if st.button("📥 Register Guest"):
69
+ if guest_cam and guest_id_photo and guest_name and room_number:
70
+ image_np = np.array(Image.open(guest_cam))
71
+ img_url = upload_image_to_drive(image_np, f"GUEST")
72
+ id_bytes = guest_id_photo.read()
73
+ id_np = np.array(Image.open(io.BytesIO(id_bytes)))
74
+ id_url = upload_image_to_drive(id_np, f"GUEST_ID")
75
 
76
  try:
77
+ # 1. Update Room
78
+ rooms = sf.query_all(f"SELECT Id FROM Room__c WHERE Name = '{room_number}'")
79
+ if rooms['totalSize'] == 0:
80
+ room_rec = sf.Room__c.create({'Name': room_number})
81
+ room_id = room_rec['id']
82
+ else:
83
+ room_id = rooms['records'][0]['Id']
84
+
85
+ # 2. Create Guest record
86
+ guest_data = {
87
+ 'Name': guest_name,
88
+ 'Mobile__c': guest_mobile,
89
+ 'Email__c': guest_email,
90
+ 'Room__c': room_id,
91
+ 'Image_Link__c': img_url,
92
+ 'ID_Proof_Link__c': id_url
93
+ }
94
+ sf.Guest__c.create(guest_data)
95
+ st.success("✅ Guest registered successfully!")
96
  except Exception as e:
97
+ st.error(f"❌ Error: {e}")
98
+ else:
99
+ st.warning("⚠️ Please complete all fields and capture/upload images.")
100
 
101
  with tab2:
102
+ st.subheader("Staff Registration")
103
+ staff_name = st.text_input("Staff Full Name")
104
+ staff_role = st.text_input("Role / Designation")
105
+ staff_id_photo = st.file_uploader("Upload ID Card", type=["jpg", "jpeg", "png"])
106
+ staff_cam = st.camera_input("Capture Staff Photo")
107
 
108
+ if st.button("📥 Register Staff"):
109
+ if staff_cam and staff_id_photo and staff_name and staff_role:
110
+ image_np = np.array(Image.open(staff_cam))
111
+ img_url = upload_image_to_drive(image_np, f"STAFF")
112
+ id_bytes = staff_id_photo.read()
113
+ id_np = np.array(Image.open(io.BytesIO(id_bytes)))
114
+ id_url = upload_image_to_drive(id_np, f"STAFF_ID")
 
115
 
116
  try:
117
+ staff_data = {
118
+ 'Name': staff_name,
119
+ 'Role__c': staff_role,
120
+ 'Image_Link__c': img_url,
121
+ 'ID_Card_Link__c': id_url
122
+ }
123
+ sf.Staff__c.create(staff_data)
124
+ st.success("✅ Staff registered successfully!")
125
  except Exception as e:
126
+ st.error(f"❌ Error: {e}")
127
+ else:
128
+ st.warning("⚠️ Please complete all fields and capture/upload images.")