File size: 4,028 Bytes
6c1bc8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211d0c3
 
6c1bc8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import os
from flask import Flask, request, send_from_directory
from twilio.twiml.messaging_response import MessagingResponse
from dotenv import load_dotenv
import logging
from datetime import datetime
import pytz

# ---------------------------------------
# LOAD ENVIRONMENT VARIABLES
# ---------------------------------------
load_dotenv()

# IMPORTANT:
# Put your Twilio details inside Hugging Face Space β†’ Settings β†’ Secrets
TWILIO_ACCOUNT_SID = os.getenv("ACd80b022c6634665f76332e678569025f")   # place Twilio SID here
TWILIO_AUTH_TOKEN = os.getenv("aea11fa641608536cbf71bb4dfb6474a")     # place Twilio token here
TWILIO_PHONE_NUMBER = os.getenv("8660712308") # WhatsApp number

# Space public URL (required for sending back static image links)
NGROK_URL = os.getenv("https://guruthetechie-ai_Virtual_tryon.hf.space/
", "")  # Example: https://your-user.hf.space/
if NGROK_URL and not NGROK_URL.endswith("/"):
    NGROK_URL += "/"

# ---------------------------------------
# FLASK APP
# ---------------------------------------
app = Flask(__name__)

# ---------------------------------------
# LOGGING (Fix for HF Spaces)
# ---------------------------------------
log_format = "%(asctime)s - %(levelname)s - %(message)s"
log_directory = "logs"
os.makedirs(log_directory, exist_ok=True)

log_file = os.path.join(log_directory, "app.log")
logging.basicConfig(filename=log_file, level=logging.INFO, format=log_format)

# ---------------------------------------
# IMPORT LOCAL MODULES
# ---------------------------------------
from python.business_logic import business_logic
from python.utils import (
    safe_extract_number,
    process_uploaded_media,
    serve_static_file,
    session_status,
    forget_user,
)

# ---------------------------------------
# TIME ZONE EXAMPLE (not required but kept)
# ---------------------------------------
ist = pytz.timezone('Asia/Kolkata')
current_datetime = datetime.now(ist)

# ---------------------------------------
# DEFAULT ROUTE β†’ TWILIO WEBHOOK
# ---------------------------------------
@app.route("/", methods=["GET", "POST"])
def chatbot():
    logging.info("πŸ“© New request received")

    resp = MessagingResponse()
    incoming_msg = request.values.get("Body", "").strip()
    media_url = request.values.get("MediaUrl0")
    media_content = None

    # Extract WhatsApp sender number
    user_number = request.values.get('From')
    if user_number:
        user_number = user_number.replace("whatsapp:", "").strip()

    logging.info(f"➑ Incoming message: {incoming_msg}")
    logging.info(f"➑ User number: {user_number}")

    # ---------------------------------------
    # IF MEDIA β†’ PROCESS UPLOAD
    # ---------------------------------------
    if media_url:
        logging.info(f"πŸ“Έ Image uploaded: {media_url}")
        media_content = process_uploaded_media(media_url, user_number)

    # ---------------------------------------
    # BUSINESS LOGIC HANDLER
    # ---------------------------------------
    reply = business_logic(
        incoming_msg=incoming_msg,
        user_number=user_number,
        media_content=media_content,
    )

    if reply:
        resp.message(reply)
    else:
        resp.message("Sorry, something went wrong. Please try again!")

    return str(resp)

# ---------------------------------------
# SERVE STATIC FILES FOR WHATSAPP LINKS
# ---------------------------------------
@app.route('/static/<path:filename>')
def serve_static(filename):
    return send_from_directory('static', filename)

# ---------------------------------------
# HEALTH CHECK ENDPOINT
# ---------------------------------------
@app.route("/health", methods=["GET"])
def health():
    return {"status": "running", "time": str(current_datetime)}

# ---------------------------------------
# RUN LOCAL ONLY
# (On Hugging Face, gunicorn runs this file)
# ---------------------------------------
if __name__ == "__main__":
    logging.info("πŸš€ Starting Flask App on port 5000...")
    app.run(host="0.0.0.0", port=5000, debug=False)