multimodalart HF Staff commited on
Commit
77b1187
·
verified ·
1 Parent(s): 765470a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -55
app.py CHANGED
@@ -8,81 +8,118 @@ from PIL import Image
8
  from io import BytesIO
9
  import tempfile
10
  import ffmpeg
11
- import json
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
- USAGE_DB_PATH = DATA_DIR / "usage_limits.json"
19
 
20
  DAILY_LIMIT = 50
 
21
 
22
- def load_usage_db() -> dict:
23
- """Load the usage database from disk."""
24
- if USAGE_DB_PATH.exists():
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 open(USAGE_DB_PATH, 'w') as f:
37
- json.dump(db, f, indent=2)
 
 
 
 
 
 
 
 
38
  except Exception as e:
39
- print(f"Error saving usage database: {e}")
 
 
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
- db = load_usage_db()
47
- today = str(date.today())
48
-
49
- # Initialize user record if not exists
50
- if username not in db:
51
- db[username] = {"date": today, "count": 0}
52
-
53
- user_data = db[username]
54
-
55
- # Reset count if it's a new day
56
- if user_data["date"] != today:
57
- user_data["date"] = today
58
- user_data["count"] = 0
59
-
60
- # Check if limit reached
61
- if user_data["count"] >= DAILY_LIMIT:
62
- return False
63
-
64
- # Increment count
65
- user_data["count"] += 1
66
- db[username] = user_data
67
- save_usage_db(db)
68
-
69
- return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  def get_remaining_generations(username: str) -> int:
72
  """Get the number of remaining generations for today."""
73
- db = load_usage_db()
74
- today = str(date.today())
75
-
76
- if username not in db:
77
- return DAILY_LIMIT
78
-
79
- user_data = db[username]
80
-
81
- # Reset if it's a new day
82
- if user_data["date"] != today:
83
- return DAILY_LIMIT
84
-
85
- return max(0, DAILY_LIMIT - user_data["count"])
 
 
 
 
 
 
 
 
 
 
 
 
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", "")