guruthetechie commited on
Commit
6c1bc8b
Β·
verified Β·
1 Parent(s): 55dcc09

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py CHANGED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from flask import Flask, request, send_from_directory
3
+ from twilio.twiml.messaging_response import MessagingResponse
4
+ from dotenv import load_dotenv
5
+ import logging
6
+ from datetime import datetime
7
+ import pytz
8
+
9
+ # ---------------------------------------
10
+ # LOAD ENVIRONMENT VARIABLES
11
+ # ---------------------------------------
12
+ load_dotenv()
13
+
14
+ # IMPORTANT:
15
+ # Put your Twilio details inside Hugging Face Space β†’ Settings β†’ Secrets
16
+ TWILIO_ACCOUNT_SID = os.getenv("ACd80b022c6634665f76332e678569025f") # place Twilio SID here
17
+ TWILIO_AUTH_TOKEN = os.getenv("aea11fa641608536cbf71bb4dfb6474a") # place Twilio token here
18
+ TWILIO_PHONE_NUMBER = os.getenv("8660712308") # WhatsApp number
19
+
20
+ # Space public URL (required for sending back static image links)
21
+ NGROK_URL = os.getenv("NGROK_URL", "") # Example: https://your-user.hf.space/
22
+ if NGROK_URL and not NGROK_URL.endswith("/"):
23
+ NGROK_URL += "/"
24
+
25
+ # ---------------------------------------
26
+ # FLASK APP
27
+ # ---------------------------------------
28
+ app = Flask(__name__)
29
+
30
+ # ---------------------------------------
31
+ # LOGGING (Fix for HF Spaces)
32
+ # ---------------------------------------
33
+ log_format = "%(asctime)s - %(levelname)s - %(message)s"
34
+ log_directory = "logs"
35
+ os.makedirs(log_directory, exist_ok=True)
36
+
37
+ log_file = os.path.join(log_directory, "app.log")
38
+ logging.basicConfig(filename=log_file, level=logging.INFO, format=log_format)
39
+
40
+ # ---------------------------------------
41
+ # IMPORT LOCAL MODULES
42
+ # ---------------------------------------
43
+ from python.business_logic import business_logic
44
+ from python.utils import (
45
+ safe_extract_number,
46
+ process_uploaded_media,
47
+ serve_static_file,
48
+ session_status,
49
+ forget_user,
50
+ )
51
+
52
+ # ---------------------------------------
53
+ # TIME ZONE EXAMPLE (not required but kept)
54
+ # ---------------------------------------
55
+ ist = pytz.timezone('Asia/Kolkata')
56
+ current_datetime = datetime.now(ist)
57
+
58
+ # ---------------------------------------
59
+ # DEFAULT ROUTE β†’ TWILIO WEBHOOK
60
+ # ---------------------------------------
61
+ @app.route("/", methods=["GET", "POST"])
62
+ def chatbot():
63
+ logging.info("πŸ“© New request received")
64
+
65
+ resp = MessagingResponse()
66
+ incoming_msg = request.values.get("Body", "").strip()
67
+ media_url = request.values.get("MediaUrl0")
68
+ media_content = None
69
+
70
+ # Extract WhatsApp sender number
71
+ user_number = request.values.get('From')
72
+ if user_number:
73
+ user_number = user_number.replace("whatsapp:", "").strip()
74
+
75
+ logging.info(f"➑ Incoming message: {incoming_msg}")
76
+ logging.info(f"➑ User number: {user_number}")
77
+
78
+ # ---------------------------------------
79
+ # IF MEDIA β†’ PROCESS UPLOAD
80
+ # ---------------------------------------
81
+ if media_url:
82
+ logging.info(f"πŸ“Έ Image uploaded: {media_url}")
83
+ media_content = process_uploaded_media(media_url, user_number)
84
+
85
+ # ---------------------------------------
86
+ # BUSINESS LOGIC HANDLER
87
+ # ---------------------------------------
88
+ reply = business_logic(
89
+ incoming_msg=incoming_msg,
90
+ user_number=user_number,
91
+ media_content=media_content,
92
+ )
93
+
94
+ if reply:
95
+ resp.message(reply)
96
+ else:
97
+ resp.message("Sorry, something went wrong. Please try again!")
98
+
99
+ return str(resp)
100
+
101
+ # ---------------------------------------
102
+ # SERVE STATIC FILES FOR WHATSAPP LINKS
103
+ # ---------------------------------------
104
+ @app.route('/static/<path:filename>')
105
+ def serve_static(filename):
106
+ return send_from_directory('static', filename)
107
+
108
+ # ---------------------------------------
109
+ # HEALTH CHECK ENDPOINT
110
+ # ---------------------------------------
111
+ @app.route("/health", methods=["GET"])
112
+ def health():
113
+ return {"status": "running", "time": str(current_datetime)}
114
+
115
+ # ---------------------------------------
116
+ # RUN LOCAL ONLY
117
+ # (On Hugging Face, gunicorn runs this file)
118
+ # ---------------------------------------
119
+ if __name__ == "__main__":
120
+ logging.info("πŸš€ Starting Flask App on port 5000...")
121
+ app.run(host="0.0.0.0", port=5000, debug=False)