File size: 16,281 Bytes
2988599 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | """
FB Auto Poster
==============
AI image generation + scheduled automatic posting to a Facebook Page.
Designed to run as a Hugging Face Gradio Space.
What it does
------------
1. Aap bahut saare prompts (ek line mein ek) daalte hain.
2. Bot har prompt se AI image generate karta hai (Hugging Face Inference API).
3. Har post ek queue mein chala jaata hai (image + caption).
4. Ek scheduler roz set kiye gaye time par queue se agli post apne aap
Facebook Page par upload kar deta hai.
Required Space secrets / env vars
---------------------------------
FB_PAGE_ID -> aapke Facebook Page ka numeric ID
FB_PAGE_ACCESS_TOKEN -> long-lived Page access token (setup guide dekhein)
HF_TOKEN -> Hugging Face token (image generate karne ke liye)
Optional env vars
-----------------
IMAGE_MODEL (default: black-forest-labs/FLUX.1-schnell)
POST_TIMES (default: 09:00,14:00,19:00 -> IST)
GRAPH_VERSION (default: v21.0)
"""
import os
import io
import json
import time
import logging
import threading
import datetime
import requests
import gradio as gr
from PIL import Image
from huggingface_hub import InferenceClient
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
# --------------------------------------------------------------------------
# Configuration
# --------------------------------------------------------------------------
FB_PAGE_ID = os.getenv("FB_PAGE_ID", "").strip()
FB_TOKEN = os.getenv("FB_PAGE_ACCESS_TOKEN", "").strip()
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
IMAGE_MODEL = os.getenv("IMAGE_MODEL", "black-forest-labs/FLUX.1-schnell").strip()
GRAPH_VER = os.getenv("GRAPH_VERSION", "v21.0").strip()
DEFAULT_TIMES = os.getenv("POST_TIMES", "09:00,14:00,19:00").strip()
TIMEZONE = os.getenv("TIMEZONE", "Asia/Kolkata").strip()
STATE_FILE = os.getenv("STATE_FILE", "state.json")
IMAGES_DIR = os.getenv("IMAGES_DIR", "generated_images")
os.makedirs(IMAGES_DIR, exist_ok=True)
# --------------------------------------------------------------------------
# Logging (kept in memory so the UI can show it)
# --------------------------------------------------------------------------
LOG_BUFFER = []
class BufferHandler(logging.Handler):
def emit(self, record):
LOG_BUFFER.append(self.format(record))
del LOG_BUFFER[:-400]
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
handlers=[logging.StreamHandler(), BufferHandler()],
)
log = logging.getLogger("autoposter")
# --------------------------------------------------------------------------
# State (queue + schedule). Persisted to a JSON file.
# --------------------------------------------------------------------------
def _default_state():
return {
"queue": [],
"times": [t.strip() for t in DEFAULT_TIMES.split(",") if t.strip()],
"enabled": False,
"history": [],
}
def load_state():
if os.path.exists(STATE_FILE):
try:
with open(STATE_FILE) as f:
data = json.load(f)
data.setdefault("queue", [])
data.setdefault("times", _default_state()["times"])
data.setdefault("enabled", False)
data.setdefault("history", [])
return data
except Exception as e:
log.warning(f"state.json padha nahi ja saka, naya bana rahe hain: {e}")
return _default_state()
def save_state(state):
with open(STATE_FILE, "w") as f:
json.dump(state, f, indent=2, ensure_ascii=False)
STATE = load_state()
LOCK = threading.RLock()
def new_id():
return int(time.time() * 1000) % 10**12
# --------------------------------------------------------------------------
# Image generation (Hugging Face Inference API)
# --------------------------------------------------------------------------
_client = None
def get_client():
global _client
if _client is None:
_client = InferenceClient(token=HF_TOKEN or None)
return _client
def generate_image(prompt):
"""Prompt se ek AI image banata hai, disk par save karta hai."""
prompt = (prompt or "").strip()
if not prompt:
raise ValueError("Prompt khaali hai")
log.info(f"Image generate ho rahi hai: {prompt[:70]}")
result = get_client().text_to_image(prompt, model=IMAGE_MODEL)
if isinstance(result, (bytes, bytearray)):
img = Image.open(io.BytesIO(result))
elif isinstance(result, Image.Image):
img = result
else:
img = Image.open(io.BytesIO(result))
path = os.path.join(IMAGES_DIR, f"img_{new_id()}.png")
img.convert("RGB").save(path)
log.info(f"Image ban gayi -> {path}")
return path, img
# --------------------------------------------------------------------------
# Facebook Graph API
# --------------------------------------------------------------------------
def _fb_check_config():
if not FB_PAGE_ID or not FB_TOKEN:
raise RuntimeError(
"FB_PAGE_ID ya FB_PAGE_ACCESS_TOKEN set nahi hai. "
"Space ke Settings -> Secrets mein daalein."
)
def _fb_result(resp):
try:
data = resp.json()
except Exception:
data = {"raw": resp.text}
if resp.status_code >= 400:
log.error(f"Facebook error {resp.status_code}: {data}")
raise RuntimeError(f"Facebook error {resp.status_code}: {data}")
log.info(f"Facebook post publish ho gaya: {data}")
return data
def fb_post_photo(image_path, caption):
"""Image + caption ko page par post karta hai."""
_fb_check_config()
url = f"https://graph.facebook.com/{GRAPH_VER}/{FB_PAGE_ID}/photos"
with open(image_path, "rb") as f:
resp = requests.post(
url,
data={"message": caption or "", "access_token": FB_TOKEN},
files={"source": f},
timeout=180,
)
return _fb_result(resp)
def fb_post_text(caption):
"""Sirf text post (bina image)."""
_fb_check_config()
url = f"https://graph.facebook.com/{GRAPH_VER}/{FB_PAGE_ID}/feed"
resp = requests.post(
url,
data={"message": caption or "", "access_token": FB_TOKEN},
timeout=60,
)
return _fb_result(resp)
def fb_page_info():
_fb_check_config()
url = f"https://graph.facebook.com/{GRAPH_VER}/{FB_PAGE_ID}"
resp = requests.get(
url, params={"fields": "name,fan_count", "access_token": FB_TOKEN}, timeout=30
)
if resp.status_code >= 400:
raise RuntimeError(f"Facebook error {resp.status_code}: {resp.text}")
return resp.json()
# --------------------------------------------------------------------------
# Scheduler
# --------------------------------------------------------------------------
scheduler = BackgroundScheduler(timezone=TIMEZONE)
def publish_next(reason="schedule"):
"""Queue se agli pending post publish karta hai."""
with LOCK:
pending = [q for q in STATE["queue"] if q.get("status") == "pending"]
if not pending:
log.info("Queue khaali hai - abhi post karne ke liye kuch nahi.")
return None
item = pending[0]
try:
if not item.get("image") or not os.path.exists(item["image"]):
path, _ = generate_image(item["prompt"])
item["image"] = path
caption = item.get("caption") or item["prompt"]
res = fb_post_photo(item["image"], caption)
item["status"] = "posted"
item["posted_at"] = datetime.datetime.now().isoformat(timespec="seconds")
item["fb_post_id"] = res.get("id") or res.get("post_id")
STATE["history"].append(
{
"time": item["posted_at"],
"caption": caption,
"image": item.get("image"),
"reason": reason,
}
)
log.info(f"POST OK ({reason}): {caption[:60]}")
except Exception as e:
item["status"] = "error"
item["error"] = str(e)
log.error(f"Post FAIL: {e}")
save_state(STATE)
return item
def rebuild_jobs(times):
scheduler.remove_all_jobs()
for t in times:
try:
hh, mm = t.strip().split(":")
scheduler.add_job(
publish_next,
CronTrigger(hour=int(hh), minute=int(mm), timezone=TIMEZONE),
kwargs={"reason": "schedule"},
id=f"job_{t}",
replace_existing=True,
)
log.info(f"Scheduled: roz {t} ({TIMEZONE})")
except Exception as e:
log.warning(f"Galat time '{t}': {e}")
if not scheduler.running and times:
scheduler.start()
# --------------------------------------------------------------------------
# UI callbacks
# --------------------------------------------------------------------------
def queue_rows():
rows = []
for q in STATE["queue"]:
rows.append(
[
q.get("id"),
q.get("status", "pending"),
(q.get("caption") or q.get("prompt") or "")[:60],
(q.get("image") or "").split("/")[-1],
]
)
return rows
def ui_generate_and_queue(prompts_text, captions_text, limit):
prompts = [p.strip() for p in (prompts_text or "").split("\n") if p.strip()]
caps = [c.strip() for c in (captions_text or "").split("\n")] if captions_text else []
if not prompts:
return [], queue_rows(), "Koi prompt nahi mila. Ek line mein ek prompt likhein."
try:
limit = int(limit)
if limit > 0:
prompts = prompts[:limit]
except Exception:
pass
previews, added = [], 0
for i, p in enumerate(prompts):
try:
path, img = generate_image(p)
except Exception as e:
log.error(f"Generate fail ('{p[:40]}'): {e}")
continue
with LOCK:
STATE["queue"].append(
{
"id": new_id(),
"prompt": p,
"caption": caps[i] if i < len(caps) else "",
"image": path,
"status": "pending",
}
)
added += 1
previews.append(img)
with LOCK:
save_state(STATE)
msg = f"{added} post queue mein add ho gaye (images ready)."
if added < len(prompts):
msg += " Kuch prompts fail hue - Logs tab dekhein."
return previews, queue_rows(), msg
def ui_start(times_text):
times = [t.strip() for t in (times_text or "").split(",") if t.strip()]
if not times:
return "Kam se kam ek time daalein, jaise: 09:00,14:00,19:00"
with LOCK:
STATE["times"] = times
STATE["enabled"] = True
save_state(STATE)
rebuild_jobs(times)
return f"Scheduler CHALU. Roz {', '.join(times)} ({TIMEZONE}) par queue se post hoga."
def ui_stop():
with LOCK:
STATE["enabled"] = False
save_state(STATE)
scheduler.remove_all_jobs()
return "Scheduler BAND kar diya. Queue safe hai."
def ui_post_now():
item = publish_next(reason="manual")
if item is None:
return "Queue khaali hai.", queue_rows()
if item.get("status") == "posted":
return f"Post ho gaya! FB id: {item.get('fb_post_id')}", queue_rows()
return f"Post fail: {item.get('error')}", queue_rows()
def ui_clear_posted():
with LOCK:
STATE["queue"] = [q for q in STATE["queue"] if q.get("status") != "posted"]
save_state(STATE)
return queue_rows(), "Posted items queue se hata diye."
def ui_reset_all():
with LOCK:
STATE["queue"] = []
STATE["history"] = []
save_state(STATE)
return queue_rows(), "Poori queue clear kar di."
def ui_logs():
return "\n".join(LOG_BUFFER[-250:]) or "(abhi koi log nahi)"
def ui_test_fb():
try:
info = fb_page_info()
return f"Facebook connected ✔ Page: {info.get('name')} | Fans: {info.get('fan_count', 'NA')}"
except Exception as e:
return f"Facebook connection fail: {e}"
# --------------------------------------------------------------------------
# Gradio UI
# --------------------------------------------------------------------------
with gr.Blocks(title="FB Auto Poster") as demo:
gr.Markdown(
"# 📮 FB Auto Poster\n"
"AI images banao aur apne Facebook Page par **roz automatic** post karo.\n\n"
"> Pehle Space ke **Secrets** mein `FB_PAGE_ID`, `FB_PAGE_ACCESS_TOKEN` aur "
"`HF_TOKEN` daalna zaroori hai (README dekhein)."
)
with gr.Tab("1️⃣ Content banayein"):
gr.Markdown(
"Ek line mein ek **prompt** likhein. Har prompt se ek image banegi aur "
"queue mein add ho jayegi. Captions optional hain - khaali chhodein to "
"prompt hi caption ban jayega."
)
with gr.Row():
prompts_in = gr.Textbox(
label="Prompts (ek line mein ek)",
lines=8,
placeholder="Diwali sale banner, bright colors, product in center\nMorning coffee flat-lay, warm tones, instagram style",
)
captions_in = gr.Textbox(
label="Captions (optional, ek line mein ek)",
lines=8,
placeholder="🪔 Diwali Dhamaka - 50% OFF!\nStart your day right ☕",
)
with gr.Row():
limit_in = gr.Number(label="Max images is baar (0 = sab)", value=0)
gen_btn = gr.Button("🖼️ Images banao & Queue mein daalo", variant="primary")
gen_status = gr.Textbox(label="Status", interactive=False)
gallery = gr.Gallery(label="Generated images", columns=4, height=320)
with gr.Tab("2️⃣ Queue & Schedule"):
gr.Markdown(
"Schedule set karein (IST). Bot roz in time par queue se agli post "
"apne aap publish karega."
)
with gr.Row():
times_in = gr.Textbox(label="Post times (comma se alag, 24h)", value="09:00,14:00,19:00")
with gr.Column():
start_btn = gr.Button("▶️ Start scheduler", variant="primary")
stop_btn = gr.Button("⏸️ Stop scheduler")
sched_status = gr.Textbox(label="Scheduler status", interactive=False)
with gr.Row():
post_now_btn = gr.Button("🚀 Post next now")
test_btn = gr.Button("🔌 Test Facebook connection")
queue_df = gr.Dataframe(
headers=["id", "status", "caption/prompt", "image"],
value=queue_rows(),
interactive=False,
label="Queue",
)
with gr.Row():
clear_btn = gr.Button("🧹 Posted items hatao")
reset_btn = gr.Button("🗑️ Poori queue clear karo")
with gr.Tab("3️⃣ Logs"):
logs_out = gr.Textbox(label="Recent logs", lines=22, interactive=False)
logs_btn = gr.Button("🔄 Refresh logs")
# wiring
gen_btn.click(
ui_generate_and_queue,
inputs=[prompts_in, captions_in, limit_in],
outputs=[gallery, queue_df, gen_status],
)
start_btn.click(ui_start, inputs=[times_in], outputs=[sched_status])
stop_btn.click(ui_stop, outputs=[sched_status])
post_now_btn.click(ui_post_now, outputs=[sched_status, queue_df])
test_btn.click(ui_test_fb, outputs=[sched_status])
clear_btn.click(ui_clear_posted, outputs=[queue_df, sched_status])
reset_btn.click(ui_reset_all, outputs=[queue_df, sched_status])
logs_btn.click(ui_logs, outputs=[logs_out])
demo.load(ui_logs, outputs=[logs_out])
# --------------------------------------------------------------------------
# Resume scheduler if it was running before a restart
# --------------------------------------------------------------------------
if STATE.get("enabled") and STATE.get("times"):
try:
rebuild_jobs(STATE["times"])
log.info("Scheduler saved state se dobara chalu kar diya.")
except Exception as e:
log.error(f"Scheduler resume fail: {e}")
if __name__ == "__main__":
demo.queue(default_concurrency_limit=2).launch()
|