Adedoyinjames commited on
Commit
4ee8d23
·
verified ·
1 Parent(s): fdee05c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -17
app.py CHANGED
@@ -24,7 +24,7 @@ headers = {
24
  def query(payload):
25
  try:
26
  response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
27
- response.raise_for_status() # Raises HTTPError for 4xx/5xx
28
  json_response = response.json()
29
  return json_response
30
  except requests.exceptions.HTTPError as http_err:
@@ -34,7 +34,7 @@ def query(payload):
34
  error_detail += f" | Details: {error_body}"
35
  except:
36
  error_detail += f" | Raw response: {response.text[:300]}"
37
- print(error_detail) # Logs to console (visible in HF Space logs)
38
  raise ValueError(error_detail)
39
  except requests.exceptions.RequestException as req_err:
40
  error_msg = f"Request failed: {req_err}"
@@ -69,16 +69,13 @@ def generate_post(topic=None):
69
 
70
  try:
71
  response = query(payload)
72
-
73
- # Debug: print full response structure (remove/comment after debugging)
74
  print("API Response:", response)
75
 
76
- # Try standard OpenAI format
77
  if "choices" in response and response["choices"]:
78
  post_content = response["choices"][0]["message"]["content"].strip()
79
  elif "error" in response:
80
  raise ValueError(f"API returned error: {response['error']}")
81
- elif isinstance(response, dict) and "content" in response: # rare fallback
82
  post_content = response["content"].strip()
83
  else:
84
  raise KeyError("Unexpected response format - no 'choices' or parsable content")
@@ -147,7 +144,7 @@ def post_to_x(content):
147
  def scheduled_post_job():
148
  global post_queue, posted_history, next_post_time
149
  if post_queue:
150
- content = post_queue.pop(0) # FIFO: first in, first out
151
  result = post_to_x(content)
152
  save_queue()
153
  if "Posted!" in result:
@@ -159,9 +156,8 @@ def scheduled_post_job():
159
  save_posted()
160
  print(f"[Scheduler] {result}\nContent: {content}")
161
 
162
- # Update next post time if queue still has items
163
  if post_queue:
164
- next_post_time = time.time() + 7200 # 2 hours in seconds
165
  else:
166
  next_post_time = None
167
 
@@ -186,10 +182,8 @@ def start_scheduler():
186
  scheduler_running = True
187
  scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
188
  scheduler_thread.start()
189
- # Post the first one immediately if queue is not empty
190
  if post_queue:
191
  scheduled_post_job()
192
- # After immediate post, set next time if still queued
193
  if post_queue:
194
  next_post_time = time.time() + 7200
195
  return "Scheduler started! Posts every 2 hours from the queue."
@@ -248,12 +242,11 @@ def add_to_queue(content):
248
  added = True
249
  if added:
250
  save_queue()
251
- # If scheduler running and was no next time, set it
252
  if scheduler_running and next_post_time is None and post_queue:
253
  next_post_time = time.time() + 7200
254
  return (
255
- "", # Clear the current post box
256
- gr.update(visible=False), # Hide Add button
257
  "\n\n".join(post_queue) if post_queue else "Queue is empty."
258
  )
259
 
@@ -290,8 +283,8 @@ with gr.Blocks(title="X Post Generator & Scheduler") as demo:
290
  refresh_btn = gr.Button("Refresh Queue & History")
291
  status_box = gr.Textbox(label="Status", value="Ready", interactive=False)
292
 
293
- # Invisible timer to update countdown every second
294
- timer = gr.Timer(every=1, active=True)
295
 
296
  # Event bindings
297
  generate_btn.click(
@@ -330,7 +323,6 @@ with gr.Blocks(title="X Post Generator & Scheduler") as demo:
330
  start_scheduler,
331
  outputs=status_box
332
  )
333
- # Also update timer on load
334
  demo.load(
335
  get_timer,
336
  outputs=timer_display
 
24
  def query(payload):
25
  try:
26
  response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
27
+ response.raise_for_status()
28
  json_response = response.json()
29
  return json_response
30
  except requests.exceptions.HTTPError as http_err:
 
34
  error_detail += f" | Details: {error_body}"
35
  except:
36
  error_detail += f" | Raw response: {response.text[:300]}"
37
+ print(error_detail)
38
  raise ValueError(error_detail)
39
  except requests.exceptions.RequestException as req_err:
40
  error_msg = f"Request failed: {req_err}"
 
69
 
70
  try:
71
  response = query(payload)
 
 
72
  print("API Response:", response)
73
 
 
74
  if "choices" in response and response["choices"]:
75
  post_content = response["choices"][0]["message"]["content"].strip()
76
  elif "error" in response:
77
  raise ValueError(f"API returned error: {response['error']}")
78
+ elif isinstance(response, dict) and "content" in response:
79
  post_content = response["content"].strip()
80
  else:
81
  raise KeyError("Unexpected response format - no 'choices' or parsable content")
 
144
  def scheduled_post_job():
145
  global post_queue, posted_history, next_post_time
146
  if post_queue:
147
+ content = post_queue.pop(0)
148
  result = post_to_x(content)
149
  save_queue()
150
  if "Posted!" in result:
 
156
  save_posted()
157
  print(f"[Scheduler] {result}\nContent: {content}")
158
 
 
159
  if post_queue:
160
+ next_post_time = time.time() + 7200
161
  else:
162
  next_post_time = None
163
 
 
182
  scheduler_running = True
183
  scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
184
  scheduler_thread.start()
 
185
  if post_queue:
186
  scheduled_post_job()
 
187
  if post_queue:
188
  next_post_time = time.time() + 7200
189
  return "Scheduler started! Posts every 2 hours from the queue."
 
242
  added = True
243
  if added:
244
  save_queue()
 
245
  if scheduler_running and next_post_time is None and post_queue:
246
  next_post_time = time.time() + 7200
247
  return (
248
+ "",
249
+ gr.update(visible=False),
250
  "\n\n".join(post_queue) if post_queue else "Queue is empty."
251
  )
252
 
 
283
  refresh_btn = gr.Button("Refresh Queue & History")
284
  status_box = gr.Textbox(label="Status", value="Ready", interactive=False)
285
 
286
+ # Invisible timer to update countdown every 1 second
287
+ timer = gr.Timer(value=1, active=True)
288
 
289
  # Event bindings
290
  generate_btn.click(
 
323
  start_scheduler,
324
  outputs=status_box
325
  )
 
326
  demo.load(
327
  get_timer,
328
  outputs=timer_display