Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,81 +8,118 @@ from PIL import Image
|
|
| 8 |
from io import BytesIO
|
| 9 |
import tempfile
|
| 10 |
import ffmpeg
|
| 11 |
-
import
|
| 12 |
from datetime import datetime, date
|
| 13 |
from pathlib import Path
|
|
|
|
| 14 |
|
| 15 |
# --- Database Setup ---
|
| 16 |
DATA_DIR = Path("/data")
|
| 17 |
DATA_DIR.mkdir(exist_ok=True)
|
| 18 |
-
|
| 19 |
|
| 20 |
DAILY_LIMIT = 50
|
|
|
|
| 21 |
|
| 22 |
-
def
|
| 23 |
-
"""
|
| 24 |
-
|
| 25 |
-
try:
|
| 26 |
-
with open(USAGE_DB_PATH, 'r') as f:
|
| 27 |
-
return json.load(f)
|
| 28 |
-
except Exception as e:
|
| 29 |
-
print(f"Error loading usage database: {e}")
|
| 30 |
-
return {}
|
| 31 |
-
return {}
|
| 32 |
-
|
| 33 |
-
def save_usage_db(db: dict):
|
| 34 |
-
"""Save the usage database to disk."""
|
| 35 |
try:
|
| 36 |
-
with
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
except Exception as e:
|
| 39 |
-
print(f"Error
|
|
|
|
|
|
|
| 40 |
|
| 41 |
def check_and_update_usage(username: str) -> bool:
|
| 42 |
"""
|
| 43 |
Check if user has reached daily limit and update usage.
|
| 44 |
Returns True if user can generate, False if limit reached.
|
| 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 |
def get_remaining_generations(username: str) -> int:
|
| 72 |
"""Get the number of remaining generations for today."""
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
# --- Google Gemini API Configuration ---
|
| 88 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
|
|
|
|
| 8 |
from io import BytesIO
|
| 9 |
import tempfile
|
| 10 |
import ffmpeg
|
| 11 |
+
import sqlite3
|
| 12 |
from datetime import datetime, date
|
| 13 |
from pathlib import Path
|
| 14 |
+
from threading import Lock
|
| 15 |
|
| 16 |
# --- Database Setup ---
|
| 17 |
DATA_DIR = Path("/data")
|
| 18 |
DATA_DIR.mkdir(exist_ok=True)
|
| 19 |
+
DB_PATH = DATA_DIR / "usage_limits.db"
|
| 20 |
|
| 21 |
DAILY_LIMIT = 50
|
| 22 |
+
db_lock = Lock()
|
| 23 |
|
| 24 |
+
def init_db():
|
| 25 |
+
"""Initialize the SQLite database."""
|
| 26 |
+
print(f"Initializing database at: {DB_PATH}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
try:
|
| 28 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 29 |
+
conn.execute('''
|
| 30 |
+
CREATE TABLE IF NOT EXISTS usage (
|
| 31 |
+
username TEXT PRIMARY KEY,
|
| 32 |
+
date TEXT NOT NULL,
|
| 33 |
+
count INTEGER NOT NULL
|
| 34 |
+
)
|
| 35 |
+
''')
|
| 36 |
+
conn.commit()
|
| 37 |
+
print("Database initialized successfully")
|
| 38 |
except Exception as e:
|
| 39 |
+
print(f"Error initializing database: {e}")
|
| 40 |
+
import traceback
|
| 41 |
+
traceback.print_exc()
|
| 42 |
|
| 43 |
def check_and_update_usage(username: str) -> bool:
|
| 44 |
"""
|
| 45 |
Check if user has reached daily limit and update usage.
|
| 46 |
Returns True if user can generate, False if limit reached.
|
| 47 |
"""
|
| 48 |
+
with db_lock:
|
| 49 |
+
try:
|
| 50 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 51 |
+
today = str(date.today())
|
| 52 |
+
cursor = conn.cursor()
|
| 53 |
+
|
| 54 |
+
# Get user record
|
| 55 |
+
cursor.execute("SELECT date, count FROM usage WHERE username = ?", (username,))
|
| 56 |
+
result = cursor.fetchone()
|
| 57 |
+
|
| 58 |
+
if result is None:
|
| 59 |
+
# New user - create record
|
| 60 |
+
cursor.execute("INSERT INTO usage (username, date, count) VALUES (?, ?, ?)",
|
| 61 |
+
(username, today, 1))
|
| 62 |
+
conn.commit()
|
| 63 |
+
print(f"New user {username}: 1/{DAILY_LIMIT}")
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
user_date, user_count = result
|
| 67 |
+
|
| 68 |
+
# Reset if new day
|
| 69 |
+
if user_date != today:
|
| 70 |
+
cursor.execute("UPDATE usage SET date = ?, count = ? WHERE username = ?",
|
| 71 |
+
(today, 1, username))
|
| 72 |
+
conn.commit()
|
| 73 |
+
print(f"User {username} reset for new day: 1/{DAILY_LIMIT}")
|
| 74 |
+
return True
|
| 75 |
+
|
| 76 |
+
# Check limit
|
| 77 |
+
if user_count >= DAILY_LIMIT:
|
| 78 |
+
print(f"User {username} reached limit: {user_count}/{DAILY_LIMIT}")
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
# Increment count
|
| 82 |
+
new_count = user_count + 1
|
| 83 |
+
cursor.execute("UPDATE usage SET count = ? WHERE username = ?",
|
| 84 |
+
(new_count, username))
|
| 85 |
+
conn.commit()
|
| 86 |
+
print(f"User {username} usage: {new_count}/{DAILY_LIMIT}")
|
| 87 |
+
return True
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"Error checking usage for {username}: {e}")
|
| 91 |
+
import traceback
|
| 92 |
+
traceback.print_exc()
|
| 93 |
+
# On error, allow the request (fail open)
|
| 94 |
+
return True
|
| 95 |
|
| 96 |
def get_remaining_generations(username: str) -> int:
|
| 97 |
"""Get the number of remaining generations for today."""
|
| 98 |
+
with db_lock:
|
| 99 |
+
try:
|
| 100 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 101 |
+
today = str(date.today())
|
| 102 |
+
cursor = conn.cursor()
|
| 103 |
+
|
| 104 |
+
cursor.execute("SELECT date, count FROM usage WHERE username = ?", (username,))
|
| 105 |
+
result = cursor.fetchone()
|
| 106 |
+
|
| 107 |
+
if result is None:
|
| 108 |
+
return DAILY_LIMIT
|
| 109 |
+
|
| 110 |
+
user_date, user_count = result
|
| 111 |
+
|
| 112 |
+
# Reset if new day
|
| 113 |
+
if user_date != today:
|
| 114 |
+
return DAILY_LIMIT
|
| 115 |
+
|
| 116 |
+
return max(0, DAILY_LIMIT - user_count)
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"Error getting remaining generations for {username}: {e}")
|
| 119 |
+
return DAILY_LIMIT
|
| 120 |
+
|
| 121 |
+
# Initialize database on module load
|
| 122 |
+
init_db()
|
| 123 |
|
| 124 |
# --- Google Gemini API Configuration ---
|
| 125 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
|