wpbcpaz commited on
Commit
ca3a811
·
verified ·
1 Parent(s): 4b608fa

Update app.py

Browse files

Atualização das funções do firebase

Files changed (1) hide show
  1. app.py +16 -41
app.py CHANGED
@@ -138,17 +138,17 @@ CACHE_DIR.mkdir(exist_ok=True)
138
  # FUNÇÕES DE PERSISTÊNCIA (FIREBASE)
139
  # ============================================
140
 
141
- # Versão para o hugging face (PARA VERSÃO COLAB O MÉTODO É DIFERENTE)
142
  def _inicializar_firestore():
 
143
  Inicializa o Firebase Admin SDK usando as credenciais
144
  armazenadas nos Secrets do Hugging Face Spaces.
145
  """
146
  global db, analytics
147
 
148
-
149
  secret_name = "FIREBASE_SERVICE_ACCOUNT_JSON"
150
  secret_json_string = os.environ.get(secret_name)
151
 
 
152
  print(f"❌ Erro de Configuração do Firebase: Secret '{secret_name}' não encontrado.")
153
  print("Usando apenas histórico de sessão (temporário).")
154
  db = None
@@ -157,12 +157,8 @@ def _inicializar_firestore():
157
 
158
  if not firebase_admin._apps:
159
  try:
160
-
161
  service_account_info = json.loads(secret_json_string)
162
-
163
-
164
  cred = credentials.Certificate(service_account_info)
165
-
166
  firebase_admin.initialize_app(cred)
167
  db = firestore.client()
168
  print("✅ Firestore inicializado com sucesso.")
@@ -174,43 +170,32 @@ def _inicializar_firestore():
174
  analytics = {"status": f"Erro de conexão: {e}"}
175
 
176
  def _adicionar_post_firestore(entry):
177
-
178
-
179
-
180
  if db:
181
  try:
182
-
183
  db.collection('posts').add(entry)
184
  return True
185
  except Exception as e:
 
 
186
  return False
187
 
188
  def _obter_historico_firestore():
189
-
190
-
191
-
192
-
193
  if db:
194
  try:
195
  posts_query = db.collection('posts').order_by('Data/Hora', direction=firestore.Query.DESCENDING).limit(100) # Aumentado limite para busca
196
-
197
  posts_stream = posts_query.stream()
198
-
199
  history = [post.to_dict() for post in posts_stream]
200
  return history
201
  except Exception as e:
 
 
202
  return []
203
 
204
  def atualizar_historico(entry):
205
  """Salva no Firestore e atualiza o cache de sessão local."""
206
-
207
-
208
  global post_history
209
-
210
-
211
  _adicionar_post_firestore(entry)
212
  # Adiciona no início da lista local
213
-
214
  post_history.insert(0, entry)
215
  # Garante que a lista local não cresça indefinidamente
216
  if len(post_history) > 100:
@@ -219,18 +204,10 @@ def atualizar_historico(entry):
219
 
220
  def carregar_historico_inicial():
221
  """Carrega o histórico do Firestore ao iniciar o app."""
222
-
223
-
224
-
225
  global post_history
226
-
227
-
228
  historico_db = _obter_historico_firestore()
229
-
230
  if historico_db:
231
  post_history = historico_db
232
-
233
-
234
  return post_history
235
 
236
  # ============================================
@@ -257,7 +234,7 @@ def _carregar_analytics_firestore():
257
  "total_imagens": 0,
258
  "cache_hits": 0,
259
  "cache_misses": 0,
260
- "total_favoritos": 0 # Adicionado
261
  }
262
  doc_ref.set(analytics)
263
  print("Analytics inicializados no Firestore.")
@@ -277,18 +254,18 @@ def _salvar_analytics_firestore():
277
  def atualizar_analytics(nicho, estilo, palavras, imagem_gerada, cache_hit, favorito):
278
  """Atualiza as métricas de analytics (agora salva no Firestore)."""
279
  global analytics
280
-
281
  analytics['total_posts'] = analytics.get('total_posts', 0) + 1
282
  analytics['total_palavras'] = analytics.get('total_palavras', 0) + palavras
283
-
284
  if imagem_gerada:
285
  analytics['total_imagens'] = analytics.get('total_imagens', 0) + 1
286
-
287
  if cache_hit:
288
  analytics['cache_hits'] = analytics.get('cache_hits', 0) + 1
289
  else:
290
  analytics['cache_misses'] = analytics.get('cache_misses', 0) + 1
291
-
292
  if favorito:
293
  analytics['total_favoritos'] = analytics.get('total_favoritos', 0) + 1
294
 
@@ -296,11 +273,11 @@ def atualizar_analytics(nicho, estilo, palavras, imagem_gerada, cache_hit, favor
296
  nicho_counts = analytics.get('posts_por_nicho', {})
297
  nicho_counts[nicho] = nicho_counts.get(nicho, 0) + 1
298
  analytics['posts_por_nicho'] = nicho_counts
299
-
300
  estilo_counts = analytics.get('posts_por_estilo', {})
301
  estilo_counts[estilo] = estilo_counts.get(estilo, 0) + 1
302
  analytics['posts_por_estilo'] = estilo_counts
303
-
304
  # Salvar no Firestore
305
  _salvar_analytics_firestore()
306
 
@@ -309,19 +286,18 @@ def gerar_relatorio_analytics():
309
  global analytics
310
  if not analytics or 'status' in analytics or analytics.get("total_posts", 0) == 0:
311
  return "📊 Nenhum post gerado ainda."
312
-
313
  # Ordenar os dicionários por valor (mais usados primeiro)
314
  posts_por_nicho_sorted = dict(sorted(analytics.get('posts_por_nicho', {}).items(), key=lambda item: item[1], reverse=True))
315
  posts_por_estilo_sorted = dict(sorted(analytics.get('posts_por_estilo', {}).items(), key=lambda item: item[1], reverse=True))
316
 
317
  total_reqs = analytics.get('cache_hits', 0) + analytics.get('cache_misses', 0)
318
  taxa_cache_hit = (analytics.get('cache_hits', 0) / total_reqs * 100) if total_reqs > 0 else 0
319
-
320
  nicho_top = max(analytics["posts_por_nicho"].items(), key=lambda x: x[1]) if analytics.get("posts_por_nicho") else ("N/A", 0)
321
  estilo_top = max(analytics["posts_por_estilo"].items(), key=lambda x: x[1]) if analytics.get("posts_por_estilo") else ("N/A", 0)
322
 
323
- relatorio = f""" **RELATÓRIO DE ANALYTICS**
324
-
325
  **Geral:**
326
  • Total de posts: {analytics['total_posts']}
327
  • Total de palavras: {analytics['total_palavras']:,}
@@ -360,7 +336,6 @@ def resetar_analytics():
360
  print("Analytics e Cache resetados.")
361
  return gerar_relatorio_analytics()
362
 
363
-
364
  # ============================================
365
  # FUNÇÕES DE CACHE
366
  # ============================================
 
138
  # FUNÇÕES DE PERSISTÊNCIA (FIREBASE)
139
  # ============================================
140
 
 
141
  def _inicializar_firestore():
142
+ """
143
  Inicializa o Firebase Admin SDK usando as credenciais
144
  armazenadas nos Secrets do Hugging Face Spaces.
145
  """
146
  global db, analytics
147
 
 
148
  secret_name = "FIREBASE_SERVICE_ACCOUNT_JSON"
149
  secret_json_string = os.environ.get(secret_name)
150
 
151
+ if not secret_json_string:
152
  print(f"❌ Erro de Configuração do Firebase: Secret '{secret_name}' não encontrado.")
153
  print("Usando apenas histórico de sessão (temporário).")
154
  db = None
 
157
 
158
  if not firebase_admin._apps:
159
  try:
 
160
  service_account_info = json.loads(secret_json_string)
 
 
161
  cred = credentials.Certificate(service_account_info)
 
162
  firebase_admin.initialize_app(cred)
163
  db = firestore.client()
164
  print("✅ Firestore inicializado com sucesso.")
 
170
  analytics = {"status": f"Erro de conexão: {e}"}
171
 
172
  def _adicionar_post_firestore(entry):
 
 
 
173
  if db:
174
  try:
 
175
  db.collection('posts').add(entry)
176
  return True
177
  except Exception as e:
178
+ print(f"❌ Erro ao adicionar post ao Firestore: {e}")
179
+ return False
180
  return False
181
 
182
  def _obter_historico_firestore():
 
 
 
 
183
  if db:
184
  try:
185
  posts_query = db.collection('posts').order_by('Data/Hora', direction=firestore.Query.DESCENDING).limit(100) # Aumentado limite para busca
 
186
  posts_stream = posts_query.stream()
 
187
  history = [post.to_dict() for post in posts_stream]
188
  return history
189
  except Exception as e:
190
+ print(f"❌ Erro ao obter histórico do Firestore: {e}")
191
+ return []
192
  return []
193
 
194
  def atualizar_historico(entry):
195
  """Salva no Firestore e atualiza o cache de sessão local."""
 
 
196
  global post_history
 
 
197
  _adicionar_post_firestore(entry)
198
  # Adiciona no início da lista local
 
199
  post_history.insert(0, entry)
200
  # Garante que a lista local não cresça indefinidamente
201
  if len(post_history) > 100:
 
204
 
205
  def carregar_historico_inicial():
206
  """Carrega o histórico do Firestore ao iniciar o app."""
 
 
 
207
  global post_history
 
 
208
  historico_db = _obter_historico_firestore()
 
209
  if historico_db:
210
  post_history = historico_db
 
 
211
  return post_history
212
 
213
  # ============================================
 
234
  "total_imagens": 0,
235
  "cache_hits": 0,
236
  "cache_misses": 0,
237
+ "total_favoritos": 0
238
  }
239
  doc_ref.set(analytics)
240
  print("Analytics inicializados no Firestore.")
 
254
  def atualizar_analytics(nicho, estilo, palavras, imagem_gerada, cache_hit, favorito):
255
  """Atualiza as métricas de analytics (agora salva no Firestore)."""
256
  global analytics
257
+
258
  analytics['total_posts'] = analytics.get('total_posts', 0) + 1
259
  analytics['total_palavras'] = analytics.get('total_palavras', 0) + palavras
260
+
261
  if imagem_gerada:
262
  analytics['total_imagens'] = analytics.get('total_imagens', 0) + 1
263
+
264
  if cache_hit:
265
  analytics['cache_hits'] = analytics.get('cache_hits', 0) + 1
266
  else:
267
  analytics['cache_misses'] = analytics.get('cache_misses', 0) + 1
268
+
269
  if favorito:
270
  analytics['total_favoritos'] = analytics.get('total_favoritos', 0) + 1
271
 
 
273
  nicho_counts = analytics.get('posts_por_nicho', {})
274
  nicho_counts[nicho] = nicho_counts.get(nicho, 0) + 1
275
  analytics['posts_por_nicho'] = nicho_counts
276
+
277
  estilo_counts = analytics.get('posts_por_estilo', {})
278
  estilo_counts[estilo] = estilo_counts.get(estilo, 0) + 1
279
  analytics['posts_por_estilo'] = estilo_counts
280
+
281
  # Salvar no Firestore
282
  _salvar_analytics_firestore()
283
 
 
286
  global analytics
287
  if not analytics or 'status' in analytics or analytics.get("total_posts", 0) == 0:
288
  return "📊 Nenhum post gerado ainda."
289
+
290
  # Ordenar os dicionários por valor (mais usados primeiro)
291
  posts_por_nicho_sorted = dict(sorted(analytics.get('posts_por_nicho', {}).items(), key=lambda item: item[1], reverse=True))
292
  posts_por_estilo_sorted = dict(sorted(analytics.get('posts_por_estilo', {}).items(), key=lambda item: item[1], reverse=True))
293
 
294
  total_reqs = analytics.get('cache_hits', 0) + analytics.get('cache_misses', 0)
295
  taxa_cache_hit = (analytics.get('cache_hits', 0) / total_reqs * 100) if total_reqs > 0 else 0
296
+
297
  nicho_top = max(analytics["posts_por_nicho"].items(), key=lambda x: x[1]) if analytics.get("posts_por_nicho") else ("N/A", 0)
298
  estilo_top = max(analytics["posts_por_estilo"].items(), key=lambda x: x[1]) if analytics.get("posts_por_estilo") else ("N/A", 0)
299
 
300
+ relatorio = f"""📊 **RELATÓRIO DE ANALYTICS**
 
301
  **Geral:**
302
  • Total de posts: {analytics['total_posts']}
303
  • Total de palavras: {analytics['total_palavras']:,}
 
336
  print("Analytics e Cache resetados.")
337
  return gerar_relatorio_analytics()
338
 
 
339
  # ============================================
340
  # FUNÇÕES DE CACHE
341
  # ============================================