File size: 16,193 Bytes
32199b1 |
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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 |
"""
β‘ Performance Optimization & Dataset Integration β‘
1. Website Loading:
- Telegram and Gmail email sending are commented out to avoid
restrictions on Hugging Face free trial spaces.
- Focus on fast page load and smooth API responses.
- Images are served from optimized folders for faster rendering.
2. Booking Data:
- All booking data is now saved directly to Hugging Face Dataset
using save_output_to_dataset().
- Local JSON file writes are disabled to reduce disk I/O and latency.
- Each booking is stored with a timestamp and full user/product info.
3. API Updates:
- search_image and search_text APIs are fully functional.
- Frontend can use these APIs without delay.
- Optimized static files are served via /optimized/ route.
Overall, these changes improve website performance, reduce dependency on
external services, and securely store all booking data in the cloud dataset.
"""
from huggingface_hub import HfApi
from datetime import datetime
from flask import Flask, request, jsonify, render_template, send_from_directory
from siglip_search_2 import search_image, search_text # β
functions for search
import os
import json
import requests
import base64
import io
import mimetypes
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
env_blob = os.environ.get("find_it_or_create", "")
secrets = {}
for line in env_blob.splitlines():
if "=" in line:
k, v = line.split("=", 1)
secrets[k.strip()] = v.strip().strip('"')
# Helper function β checks normal env first, then blob
def get_secret(key: str, default=None):
return os.environ.get(key) or secrets.get(key, default)
# -----------------------------
# Gmail SMTP settings
# -----------------------------
GMAIL_USER = get_secret("GMAIL_USER")
GMAIL_PASSWORD = get_secret("GMAIL_PASSWORD")
# -----------------------------
# Telegram bot integration
# -----------------------------
bot_token = get_secret("TELEGRAM_BOT_TOKEN")
chat_id = get_secret("TELEGRAM_CHAT_ID")
BOOKING_FILE = "bookings.json"
UPLOAD_FOLDER = "uploads"
# os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# -----------------------------
# Telegram bot integration
# -----------------------------
# bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")
# chat_id = os.environ.get("TELEGRAM_CHAT_ID")
env_blob = os.environ.get("find_it_or_create", "")
secrets = {}
for line in env_blob.splitlines():
if "=" in line:
k, v = line.split("=", 1)
secrets[k.strip()] = v.strip().strip('"')
hf_token = get_secret("HF_TOKEN")
dataset_repo = "mlbhanuprakash/data" # π your private dataset
api = HfApi()
def save_output_to_dataset(output):
# Create a timestamp-based filename (replace ':' with '-')
timestamp = datetime.now().isoformat().replace(":", "-")
filename = f"data_{timestamp}.json"
local_file = f"/tmp/{filename}"
# Prepare data to save
entry = {
"timestamp": datetime.now().isoformat(),
"output": output
}
# Write the data to a local JSON file
with open(local_file, "w") as f:
json.dump(entry, f, indent=2)
# Upload that file as a new entry in your dataset
api.upload_file(
path_or_fileobj=local_file,
path_in_repo="JSON_data/"+filename, # π unique file each time
repo_id=dataset_repo,
token=hf_token,
repo_type="dataset",
commit_message=f"Add new output file {filename}"
)
print(f"β
Output saved as {filename} in Hugging Face Dataset!")
UPLOAD_FOLDER = "/tmp" # safe writable folder in Spaces
""""
def send_email(to_email, subject, body, product_image_str=None):
msg = MIMEMultipart()
msg['From'] = GMAIL_USER
msg['To'] = to_email
msg['Subject'] = subject
# Attach text body
msg.attach(MIMEText(body, 'plain'))
# If product image is available, try attaching
if product_image_str:
try:
img_bytes = None
# Case 1: Data URI (base64)
if product_image_str.startswith("data:"):
header, b64data = product_image_str.split(",", 1)
img_bytes = base64.b64decode(b64data)
# Case 2: HTTP(S) URL β download the image
elif product_image_str.startswith("http://") or product_image_str.startswith("https://"):
resp = requests.get(product_image_str, timeout=10)
if resp.status_code == 200:
img_bytes = resp.content
# Case 3: Local file path
elif os.path.exists(product_image_str):
with open(product_image_str, "rb") as f:
img_bytes = f.read()
# If we got image bytes, attach them
if img_bytes:
image = MIMEImage(img_bytes, name="product_image.jpg")
msg.attach(image)
except Exception as e:
app.logger.error(f"Failed to attach product image: {e}")
# Send email via Gmail SMTP
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login(GMAIL_USER, GMAIL_PASSWORD)
server.sendmail(GMAIL_USER, to_email, msg.as_string())
app.logger.info(f"Email sent to {to_email}")
except Exception as e:
app.logger.error(f"Email sending failed: {e}")
return False
return True"""
# -----------------------------
# Homepage
# -----------------------------
@app.route("/")
def index():
return render_template("index.html")
# -----------------------------
# Image Search API
# -----------------------------
@app.route("/search_image", methods=["POST"])
def search_image_api():
"""Handle image upload and run SigLIP image search"""
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "Empty filename"}), 400
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(filepath)
app.logger.info(f"Received image: {filepath}")
try:
results = search_image(filepath, topk=1) # β
already working
app.logger.info(f"Returning {len(results)} image results")
except Exception as e:
app.logger.error(f"{e}")
return jsonify({"error": str(e)}), 500
return jsonify(results)
# -----------------------------
# Text Search API
# -----------------------------
@app.route("/search_text", methods=["POST"])
def search_text_api():
"""Handle text query and run SigLIP text search"""
data = request.get_json()
query = data.get("query") if data else None
if not query:
return jsonify({"error": "No search query provided"}), 400
app.logger.info(f"Received text query: {query}")
try:
results = search_text(query, topk=5) # β
now works like image search
app.logger.info(f"Returning {len(results)} text results")
except Exception as e:
app.logger.error(f"{e}")
return jsonify({"error": str(e)}), 500
return jsonify(results)
# -----------------------------
# Booking Save API
# -----------------------------
@app.route("/save_booking", methods=["POST"])
def save_booking():
data = request.get_json()
if not data:
return jsonify({"error": "No data received"}), 400
# Attach the search info (front-end may send productImage OR productResult)
product = data.get("productResult", {}) # object from search result (optional)
# Prefer productImage sent directly, fallback:
product_image_str = (data.get("productImage")
or product.get("image_url")
or product.get("uploaded_image")
or "")
saved_data = {
"name": data.get("name"),
"email": data.get("email"),
"phone": data.get("phone"),
"location": data.get("location"),
"chest": data.get("chest"),
"waist": data.get("waist"),
"shoulder": data.get("shoulder"),
"sleeve": data.get("sleeve"),
"selected Size": data.get("selectedSize"),
"product Image": product_image_str,
"search Query": (product.get("search_query") or data.get("searchQuery") or ""),
"designer ID/Employee ID ": data.get("designerID"),
"designer Name": data.get("designerName")
}
if os.path.exists(BOOKING_FILE):
with open(BOOKING_FILE, "r", encoding="utf-8") as f:
try:
bookings = json.load(f)
except json.JSONDecodeError:
bookings = []
else:
bookings = []
save_output_to_dataset(saved_data)
"""
bookings.append(saved_data)
# with open(BOOKING_FILE, "w", encoding="utf-8") as f:
# json.dump(bookings, f, indent=2, ensure_ascii=False)
print("sssssssssssssssssssssssssss",saved_data)
subject = f"New Task Assigned: {saved_data.get('name')}"
# -----------------------------
# Telegram message & photo sending
# -----------------------------
global bot_token, chat_id
message = (
f"π’ *New Task Assignment* π’\n\n"
f"Hello {saved_data.get('designer Name')},\n\n"
f"Assigned Designer: {saved_data.get('designer Name')} (Employee ID: {saved_data.get('designer ID/Employee ID ')})\n\n"
f"A new customer request has been assigned to you automatically by our system.\n\n"
f"--- π€ Customer Details ---\n"
f"Name: {saved_data.get('name')}\n"
f"Email: {saved_data.get('email')}\n"
f"Phone: {saved_data.get('phone')}\n"
f"Location: {saved_data.get('location')}\n\n"
f"--- π Measurements ---\n"
f"Chest: {saved_data.get('chest')} in\n"
f"Waist: {saved_data.get('waist')} in\n"
f"Shoulder: {saved_data.get('shoulder')} in\n"
f"Sleeve: {saved_data.get('sleeve')} in\n"
f"Selected Size: {saved_data.get('selected Size')}\n\n"
f"--- ποΈ Product Details ---\n"
f"Search Query: {saved_data.get('search Query')}\n\n"
f"--- π Assignment Info ---\n"
f"Task generated automatically by system bot.\n\n"
f"If you have any queries, please reach out to Krish (Team Lead).\n\n"
f"β‘ Please proceed with this task at your earliest convenience.\n\n"
f"Thank you! π"
)
body = message"""
# TELEGRAM_BOT
"""
if product_image_str:
try:
# Data URI
if product_image_str.startswith("data:"):
header, b64data = product_image_str.split(",", 1)
img_bytes = base64.b64decode(b64data)
mime = "image/jpeg"
try:
mime = header.split(";")[0].split(":")[1]
except Exception:
pass
ext = mimetypes.guess_extension(mime) or ".jpg"
filename = f"photo{ext}"
bio = io.BytesIO(img_bytes)
bio.name = filename
files = {'photo': (filename, bio, mime)}
resp = requests.post(
f'https://api.telegram.org/bot{bot_token}/sendPhoto',
data={'chat_id': chat_id, 'caption': f"Product image for {message}"},
files=files,
timeout=30
)
if resp.status_code != 200:
app.logger.error("Telegram sendPhoto (data URI) failed: %s %s", resp.status_code, resp.text)
# HTTP(S) URL
elif product_image_str.startswith("http://") or product_image_str.startswith("https://"):
resp = requests.post(
f'https://api.telegram.org/bot{bot_token}/sendPhoto',
data={'chat_id': chat_id, 'photo': product_image_str, 'caption': f"Product image for {saved_data.get('name')}"},
timeout=15
)
if resp.status_code != 200:
app.logger.error("Telegram sendPhoto (URL) returned %s: %s", resp.status_code, resp.text)
requests.get(
f'https://api.telegram.org/bot{bot_token}/sendMessage',
params={'chat_id': chat_id, 'text': message},
timeout=10
)
# Local file or path
else:
candidates = [
product_image_str,
os.path.join(os.getcwd(), product_image_str),
os.path.join(os.getcwd(), UPLOAD_FOLDER, os.path.basename(product_image_str)),
os.path.join(os.getcwd(), 'images', os.path.basename(product_image_str))
]
found = None
for p in candidates:
if p and os.path.exists(p):
found = p
break
if found:
with open(found, 'rb') as photo_f:
filename = os.path.basename(found)
mime = mimetypes.guess_type(found)[0] or 'application/octet-stream'
files = {'photo': (filename, photo_f, mime)}
resp = requests.post(
f'https://api.telegram.org/bot{bot_token}/sendPhoto',
data={'chat_id': chat_id, 'caption': f"Product image for {saved_data.get('name')}"},
files=files,
timeout=30
)
if resp.status_code != 200:
app.logger.error("Telegram sendPhoto (local) returned %s: %s", resp.status_code, resp.text)
else:
try:
base = request.host_url.rstrip('/')
photo_url = base + '/' + product_image_str.lstrip('/')
resp = requests.post(
f'https://api.telegram.org/bot{bot_token}/sendPhoto',
data={'chat_id': chat_id, 'photo': photo_url, 'caption': f"Product image for {saved_data.get('name')}"},
timeout=15
)
if resp.status_code != 200:
app.logger.error("Telegram sendPhoto (fallback URL) returned %s: %s", resp.status_code, resp.text)
except Exception as e:
app.logger.error("Telegram fallback URL attempt failed: %s", e)
except Exception as e:
app.logger.exception("Telegram photo send failed: %s", e)
else:
requests.get(
f'https://api.telegram.org/bot{bot_token}/sendMessage',
params={'chat_id': chat_id, 'text': message},
timeout=10
)
# Send email
email_sent = send_email("bbhanu410@gmail.com", subject, body, product_image_str)
if not email_sent:
return jsonify({"error": "Booking saved but email failed"}), 500
"""
return jsonify({"message": "Booking successfully saved"})
# -----------------------------
# Serve Static Files
# -----------------------------
@app.route("/optimized/<path:filename>")
def serve_images(filename):
return send_from_directory("images", filename)
@app.route("/uploads/<path:filename>")
def serve_uploads(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
# -----------------------------
# Run App
# -----------------------------
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)), debug=True) |