random2222 commited on
Commit
1ca2a2d
·
verified ·
1 Parent(s): 9edf764

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -26
app.py CHANGED
@@ -97,42 +97,43 @@ cv2.ocl.setUseOpenCL(True)
97
  class UsageLogger:
98
  """Simple logger to record app usage timestamps"""
99
  def __init__(self, log_filename="usage_logs.json"):
100
- # Get the current working directory for the application
101
- try:
102
- # Create logs directory if it doesn't exist
103
- self.logs_dir = os.path.join(os.getcwd(), "logs")
104
- os.makedirs(self.logs_dir, exist_ok=True)
105
- self.log_file = os.path.join(self.logs_dir, log_filename)
106
- except Exception as e:
107
- # Fallback to a directory we should have write access to
108
- print(f"Error creating logs directory: {str(e)}")
109
- temp_dir = tempfile.gettempdir()
110
- self.logs_dir = os.path.join(temp_dir, "image_processor_logs")
111
- os.makedirs(self.logs_dir, exist_ok=True)
112
- self.log_file = os.path.join(self.logs_dir, log_filename)
113
 
114
  print(f"Log file location: {self.log_file}")
115
  self.ensure_log_file_exists()
116
 
117
  def ensure_log_file_exists(self):
118
  """Create log file with empty array if it doesn't exist"""
 
 
 
119
  try:
120
  if not os.path.exists(self.log_file):
121
  with open(self.log_file, 'w') as f:
122
- json.dump({"visits": []}, f)
123
  # Test if file is readable/writable
124
  with open(self.log_file, 'r+') as f:
125
  pass
126
  except Exception as e:
127
  print(f"Error accessing log file: {str(e)}")
128
- # Create a new log file in a different location as fallback
129
- self.log_file = os.path.join(tempfile.gettempdir(), "image_processor_logs.json")
130
  print(f"Using fallback log file: {self.log_file}")
131
  with open(self.log_file, 'w') as f:
132
- json.dump({"visits": []}, f)
133
 
134
  def log_visit(self):
135
  """Log a timestamp when the app is visited/used"""
 
 
 
 
136
  current_time = datetime.datetime.now().isoformat()
137
 
138
  try:
@@ -145,10 +146,10 @@ class UsageLogger:
145
  with open(self.log_file, 'r') as f:
146
  logs = json.load(f)
147
  else:
148
- logs = {"visits": []}
149
  except (json.JSONDecodeError, FileNotFoundError):
150
  # If file is corrupt or doesn't exist, start fresh
151
- logs = {"visits": []}
152
 
153
  # Append new timestamp
154
  logs["visits"].append({"timestamp": current_time})
@@ -163,10 +164,35 @@ class UsageLogger:
163
  print(f"Error logging visit: {str(e)}")
164
  return False
165
 
166
- def log_usage(self, feature_type):
167
- """Log when a specific feature is used"""
 
 
 
 
 
 
 
 
168
  current_time = datetime.datetime.now().isoformat()
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  try:
171
  # Make sure log directory exists
172
  os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
@@ -177,22 +203,28 @@ class UsageLogger:
177
  with open(self.log_file, 'r') as f:
178
  logs = json.load(f)
179
  else:
180
- logs = {"visits": []}
181
  except (json.JSONDecodeError, FileNotFoundError):
182
  # If file is corrupt or doesn't exist, start fresh
183
- logs = {"visits": []}
 
 
 
 
184
 
185
  # Append new usage record
186
- logs["visits"].append({
187
  "timestamp": current_time,
188
- "feature": feature_type
 
 
189
  })
190
 
191
  # Write updated logs
192
  with open(self.log_file, 'w') as f:
193
  json.dump(logs, f, indent=2)
194
 
195
- print(f"Feature usage logged: {feature_type} at {current_time}")
196
  return True
197
  except Exception as e:
198
  print(f"Error logging usage: {str(e)}")
 
97
  class UsageLogger:
98
  """Simple logger to record app usage timestamps"""
99
  def __init__(self, log_filename="usage_logs.json"):
100
+ # Use the persistent storage directory in Hugging Face Spaces
101
+ import os
102
+
103
+ # Hugging Face Spaces persistent storage path
104
+ self.logs_dir = os.path.join("/home/user/app", "logs")
105
+ os.makedirs(self.logs_dir, exist_ok=True)
106
+ self.log_file = os.path.join(self.logs_dir, log_filename)
 
 
 
 
 
 
107
 
108
  print(f"Log file location: {self.log_file}")
109
  self.ensure_log_file_exists()
110
 
111
  def ensure_log_file_exists(self):
112
  """Create log file with empty array if it doesn't exist"""
113
+ import os
114
+ import json
115
+
116
  try:
117
  if not os.path.exists(self.log_file):
118
  with open(self.log_file, 'w') as f:
119
+ json.dump({"visits": [], "features": []}, f)
120
  # Test if file is readable/writable
121
  with open(self.log_file, 'r+') as f:
122
  pass
123
  except Exception as e:
124
  print(f"Error accessing log file: {str(e)}")
125
+ # Try to create a logs.json file directly in the app root
126
+ self.log_file = "/home/user/app/logs.json"
127
  print(f"Using fallback log file: {self.log_file}")
128
  with open(self.log_file, 'w') as f:
129
+ json.dump({"visits": [], "features": []}, f)
130
 
131
  def log_visit(self):
132
  """Log a timestamp when the app is visited/used"""
133
+ import datetime
134
+ import json
135
+ import os
136
+
137
  current_time = datetime.datetime.now().isoformat()
138
 
139
  try:
 
146
  with open(self.log_file, 'r') as f:
147
  logs = json.load(f)
148
  else:
149
+ logs = {"visits": [], "features": []}
150
  except (json.JSONDecodeError, FileNotFoundError):
151
  # If file is corrupt or doesn't exist, start fresh
152
+ logs = {"visits": [], "features": []}
153
 
154
  # Append new timestamp
155
  logs["visits"].append({"timestamp": current_time})
 
164
  print(f"Error logging visit: {str(e)}")
165
  return False
166
 
167
+ def log_usage(self, feature_type, media_type=None):
168
+ """Log when a specific feature is used
169
+ Args:
170
+ feature_type: The feature used (e.g., 'black_white_image', 'sketch_video')
171
+ media_type: The type of media processed (e.g., 'image', 'video')
172
+ """
173
+ import datetime
174
+ import json
175
+ import os
176
+
177
  current_time = datetime.datetime.now().isoformat()
178
 
179
+ # Extract media type from feature name if not provided
180
+ if media_type is None:
181
+ if "image" in feature_type:
182
+ media_type = "image"
183
+ elif "video" in feature_type:
184
+ media_type = "video"
185
+ else:
186
+ media_type = "unknown"
187
+
188
+ # Extract service type
189
+ if "black_white" in feature_type:
190
+ service_type = "black_and_white"
191
+ elif "sketch" in feature_type:
192
+ service_type = "pencil_sketch"
193
+ else:
194
+ service_type = "unknown"
195
+
196
  try:
197
  # Make sure log directory exists
198
  os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
 
203
  with open(self.log_file, 'r') as f:
204
  logs = json.load(f)
205
  else:
206
+ logs = {"visits": [], "features": []}
207
  except (json.JSONDecodeError, FileNotFoundError):
208
  # If file is corrupt or doesn't exist, start fresh
209
+ logs = {"visits": [], "features": []}
210
+
211
+ # Make sure features key exists
212
+ if "features" not in logs:
213
+ logs["features"] = []
214
 
215
  # Append new usage record
216
+ logs["features"].append({
217
  "timestamp": current_time,
218
+ "feature": feature_type,
219
+ "service": service_type,
220
+ "media_type": media_type
221
  })
222
 
223
  # Write updated logs
224
  with open(self.log_file, 'w') as f:
225
  json.dump(logs, f, indent=2)
226
 
227
+ print(f"Feature usage logged: {feature_type} ({media_type}) at {current_time}")
228
  return True
229
  except Exception as e:
230
  print(f"Error logging usage: {str(e)}")