Spaces:
Sleeping
Sleeping
hf-actions
commited on
Commit
·
ca2863a
0
Parent(s):
Clean commit: remove virtualenv and large files
Browse files- .gitignore +30 -0
- HF_AUTH.md +58 -0
- README.md +104 -0
- app.py +162 -0
- check_hf.py +26 -0
- create_space_and_push.py +17 -0
- deploy_hf_space.py +104 -0
- exchange_tokens.py +166 -0
- generate_image.py +504 -0
- generate_wisdom.py +107 -0
- hf_auth_setup.py +73 -0
- post_to_facebook.py +72 -0
- push_to_space.py +22 -0
- push_upload_to_space.py +28 -0
- replicate_daily_job.py +9 -0
- requirements.txt +6 -0
- run_generate_and_post.py +7 -0
.gitignore
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
generated_images/
|
| 5 |
+
.vscode/
|
| 6 |
+
dist/
|
| 7 |
+
build/
|
| 8 |
+
.DS_Store
|
| 9 |
+
venv/
|
| 10 |
+
env/
|
| 11 |
+
.venv/
|
| 12 |
+
.venv
|
| 13 |
+
*.egg-info/
|
| 14 |
+
# Ignore environment and secrets
|
| 15 |
+
.env
|
| 16 |
+
.env.bak
|
| 17 |
+
|
| 18 |
+
# Python cache
|
| 19 |
+
__pycache__/
|
| 20 |
+
*.py[cod]
|
| 21 |
+
|
| 22 |
+
# Generated images
|
| 23 |
+
generated_images/
|
| 24 |
+
|
| 25 |
+
# VS Code
|
| 26 |
+
.vscode/
|
| 27 |
+
|
| 28 |
+
# OS files
|
| 29 |
+
Thumbs.db
|
| 30 |
+
.DS_Store
|
HF_AUTH.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hugging Face Space authentication (quick guide)
|
| 2 |
+
|
| 3 |
+
This repo can be pushed to a Hugging Face Space. Below are minimal steps to authenticate and configure your local folder so `git push` to the Space works.
|
| 4 |
+
|
| 5 |
+
1) Install the CLI (in your venv)
|
| 6 |
+
|
| 7 |
+
```powershell
|
| 8 |
+
pip install --upgrade huggingface_hub
|
| 9 |
+
# optional CLI helper
|
| 10 |
+
pip install --upgrade huggingface-hub[cli]
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
2) Login interactively (recommended)
|
| 14 |
+
|
| 15 |
+
```powershell
|
| 16 |
+
huggingface-cli login
|
| 17 |
+
# then paste your HF token when prompted
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
3) Or set token in `.env` (non-interactive)
|
| 21 |
+
|
| 22 |
+
Add one of these lines to your `.env` (already used by helper scripts):
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
HF_TOKEN=hf_xxx...
|
| 26 |
+
HUGGINGFACEHUB_API_TOKEN=hf_xxx...
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
4) Use the helper script to configure git remote (optional)
|
| 30 |
+
|
| 31 |
+
Run in repo root (will print suggested remote and can add it):
|
| 32 |
+
|
| 33 |
+
```powershell
|
| 34 |
+
python hf_auth_setup.py
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Or manually add remote (replace `<token>`, `<username>`, `<repo>`):
|
| 38 |
+
|
| 39 |
+
```powershell
|
| 40 |
+
git remote remove origin --no-optional || true
|
| 41 |
+
git remote add origin https://<token>@huggingface.co/spaces/<username>/<repo>.git
|
| 42 |
+
git push -u origin main
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Note: embedding the token in the remote URL is convenient but the token will be visible in your local git config. Use `huggingface-cli login` or a credential helper for more secure usage.
|
| 46 |
+
|
| 47 |
+
5) Space runtime Secrets
|
| 48 |
+
|
| 49 |
+
In the Hugging Face Space UI set the following Secrets (Settings → Secrets):
|
| 50 |
+
- `FB_PAGE_ACCESS_TOKEN`
|
| 51 |
+
- `FB_PAGE_ID`
|
| 52 |
+
- `REPLICATE_API_TOKEN`
|
| 53 |
+
- `OPENAI_API_KEY` (if used)
|
| 54 |
+
- `RUN_DAILY_REPLICATE` (set to `true` to enable scheduled runs)
|
| 55 |
+
|
| 56 |
+
6) Troubleshooting
|
| 57 |
+
- If `git push` fails with 403, verify the token scope and that the token is valid.
|
| 58 |
+
- You can create a new token at: https://huggingface.co/settings/tokens (grant `read` and `write` as needed for repo creation/push).
|
README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Wisdom Poster
|
| 3 |
+
emoji: "🪷"
|
| 4 |
+
colorFrom: "indigo"
|
| 5 |
+
colorTo: "teal"
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: "3.50.0"
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Wisdom Poster — Hugging Face Space
|
| 13 |
+
|
| 14 |
+
This Space generates short wisdom text and a matching image, then posts the result to a Facebook Page. The app supports both OpenAI and Replicate image generation; it will try providers in the order configured by the `PROVIDER_ORDER` environment variable (default: `openai,replicate`).
|
| 15 |
+
|
| 16 |
+
Quick setup (local)
|
| 17 |
+
|
| 18 |
+
1. Install dependencies:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
python -m pip install -r requirements.txt
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
2. Create a local `.env` (do NOT commit it). Example keys used by the app:
|
| 25 |
+
|
| 26 |
+
- `FB_PAGE_ID` — the numeric Page ID
|
| 27 |
+
- `FB_PAGE_ACCESS_TOKEN` — a Page access token with `pages_manage_posts` / publish permissions
|
| 28 |
+
- `OPENAI_API_KEY` — (optional) OpenAI API key if using OpenAI image generation
|
| 29 |
+
- `REPLICATE_API_TOKEN` — (optional) Replicate API key if using Replicate
|
| 30 |
+
- `REPLICATE_MODEL` — (optional) default replicate model ref (owner/name:version), e.g. `google/nano-banana`
|
| 31 |
+
- `PROVIDER_ORDER` — (optional) e.g. `replicate,openai` or `openai,replicate` (default `openai,replicate`)
|
| 32 |
+
- `RUN_DAILY_REPLICATE` — (optional) `true` to enable scheduled daily runs inside `app.py`
|
| 33 |
+
- `DAILY_INTERVAL_HOURS` — (optional) schedule interval in hours (default `24`)
|
| 34 |
+
- `DAILY_PROMPT` — (optional) override prompt for scheduled runs
|
| 35 |
+
|
| 36 |
+
Deploying to Hugging Face Spaces
|
| 37 |
+
|
| 38 |
+
1. In your Space settings, set the following Secrets (Settings → Secrets):
|
| 39 |
+
|
| 40 |
+
- `FB_PAGE_ACCESS_TOKEN`
|
| 41 |
+
- `FB_PAGE_ID`
|
| 42 |
+
- `REPLICATE_API_TOKEN` (if you plan to use Replicate)
|
| 43 |
+
- `OPENAI_API_KEY` (if you plan to use OpenAI)
|
| 44 |
+
- `PROVIDER_ORDER` (optional)
|
| 45 |
+
- `RUN_DAILY_REPLICATE` (set to `true` to enable daily runs)
|
| 46 |
+
|
| 47 |
+
2. Ensure `app.py` and `requirements.txt` are present at the repository root. The Space entrypoint is `app.py` (specified in the metadata above).
|
| 48 |
+
|
| 49 |
+
Notes and recommendations
|
| 50 |
+
|
| 51 |
+
- The app spawns a daemon background thread for scheduled runs when `RUN_DAILY_REPLICATE` is enabled. This works while the Space process is active but can be interrupted during redeploys — for guaranteed scheduling, use an external scheduler.
|
| 52 |
+
- Keep your Space private if you do not want the public to access the UI or to expose functionality.
|
| 53 |
+
- Monitor usage and API costs for OpenAI/Replicate.
|
| 54 |
+
|
| 55 |
+
Troubleshooting
|
| 56 |
+
|
| 57 |
+
- If the Space fails to start, check the `requirements.txt` includes all needed packages and that Secrets are set.
|
| 58 |
+
- Use the Space logs (Settings → Logs) to inspect runtime errors.
|
| 59 |
+
|
| 60 |
+
Minimal files to leave in the Space repo
|
| 61 |
+
|
| 62 |
+
- `app.py` (entrypoint)
|
| 63 |
+
- `requirements.txt`
|
| 64 |
+
- `generate_image.py`, `generate_wisdom.py`, `post_to_facebook.py`
|
| 65 |
+
- `.gitignore` (ignore `.env`, generated images)
|
| 66 |
+
|
| 67 |
+
If you want, I can also add a short *Deploy checklist* file with exact steps and screenshot guidance for adding Secrets in the HF UI.
|
| 68 |
+
# Post to Facebook Page
|
| 69 |
+
|
| 70 |
+
This repository includes a small Python script to post a message to a Facebook Page using a Page Access Token stored in a `.env` file.
|
| 71 |
+
|
| 72 |
+
Setup
|
| 73 |
+
|
| 74 |
+
1. Install dependencies:
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
python -m pip install -r requirements.txt
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
2. Populate your `.env` (do not commit secrets). Example keys used by the script:
|
| 81 |
+
|
| 82 |
+
- `FB_PAGE_ID` — the numeric Page ID
|
| 83 |
+
- `FB_PAGE_ACCESS_TOKEN` — a Page access token with `pages_manage_posts` or appropriate publish permissions
|
| 84 |
+
- `MESSAGE` — optional default message
|
| 85 |
+
- `LINK` — optional link to attach
|
| 86 |
+
|
| 87 |
+
Usage
|
| 88 |
+
|
| 89 |
+
Run directly with a message:
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
python post_to_facebook.py --message "Hello from script"
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
Or rely on `MESSAGE` in `.env`:
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
python post_to_facebook.py
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Notes
|
| 102 |
+
|
| 103 |
+
- The script posts to the Graph API endpoint `/{page-id}/feed`.
|
| 104 |
+
- If you need long-lived tokens or other flows, exchange tokens using Facebook's API before placing them in `.env`.
|
app.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import threading
|
| 6 |
+
import requests
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
load_dotenv()
|
| 10 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
from generate_wisdom import generate_wisdom
|
| 14 |
+
from post_to_facebook import post_to_facebook
|
| 15 |
+
from generate_image import generate_image, generate_and_post
|
| 16 |
+
from generate_image import generate_and_post
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def generate_and_optionally_post(topic: str, do_post: bool):
|
| 20 |
+
try:
|
| 21 |
+
logger.info("Generating wisdom for topic: %s", topic)
|
| 22 |
+
wisdom = generate_wisdom(topic)
|
| 23 |
+
except Exception as e:
|
| 24 |
+
logger.exception("Failed to generate wisdom: %s", e)
|
| 25 |
+
return "Error generating wisdom: " + str(e), ""
|
| 26 |
+
|
| 27 |
+
if do_post:
|
| 28 |
+
page_id = os.getenv("FB_PAGE_ID")
|
| 29 |
+
token = os.getenv("FB_PAGE_ACCESS_TOKEN")
|
| 30 |
+
if not page_id or not token:
|
| 31 |
+
logger.error("Missing Facebook credentials in environment")
|
| 32 |
+
return wisdom, "Missing FB_PAGE_ID or FB_PAGE_ACCESS_TOKEN in environment"
|
| 33 |
+
try:
|
| 34 |
+
logger.info("Posting wisdom to Facebook page %s", page_id)
|
| 35 |
+
res = post_to_facebook(page_id, token, wisdom)
|
| 36 |
+
status = f"Posted to Facebook: {res.get('id') if isinstance(res, dict) else res}"
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.exception("Failed to post to Facebook: %s", e)
|
| 39 |
+
status = "Failed to post to Facebook: " + str(e)
|
| 40 |
+
else:
|
| 41 |
+
status = "Not posted (preview only)"
|
| 42 |
+
|
| 43 |
+
return wisdom, status
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
with gr.Blocks() as demo:
|
| 47 |
+
gr.Markdown("# Buddhism Wisdom Generator & Facebook Poster")
|
| 48 |
+
with gr.Row():
|
| 49 |
+
topic = gr.Textbox(label="Topic (optional)", placeholder="e.g. mindfulness, compassion")
|
| 50 |
+
do_post = gr.Checkbox(label="Post to Facebook", value=False)
|
| 51 |
+
with gr.Row():
|
| 52 |
+
image_prompt = gr.Textbox(label="Image prompt (optional)", placeholder="Prompt for image generation")
|
| 53 |
+
image_post = gr.Checkbox(label="Post image to Facebook", value=False)
|
| 54 |
+
force_replicate = gr.Checkbox(label="Force Replicate", value=False)
|
| 55 |
+
use_wisdom_for_image = gr.Checkbox(label="Use generated wisdom as image prompt", value=True)
|
| 56 |
+
generate_btn = gr.Button("Generate & Post")
|
| 57 |
+
output_text = gr.Textbox(label="Generated Wisdom", lines=3)
|
| 58 |
+
status = gr.Textbox(label="Status", lines=2)
|
| 59 |
+
|
| 60 |
+
img_btn = gr.Button("Generate Image & Post")
|
| 61 |
+
img_output = gr.Image(label="Generated Image")
|
| 62 |
+
img_status = gr.Textbox(label="Image Status", lines=2)
|
| 63 |
+
|
| 64 |
+
generate_btn.click(fn=generate_and_optionally_post, inputs=[topic, do_post], outputs=[output_text, status])
|
| 65 |
+
def _gen_img(prompt, do_post, use_wisdom, force_replicate):
|
| 66 |
+
if not prompt and not use_wisdom:
|
| 67 |
+
return None, "No image prompt provided and not using wisdom"
|
| 68 |
+
try:
|
| 69 |
+
provider_order = None
|
| 70 |
+
if force_replicate:
|
| 71 |
+
provider_order = "replicate,openai"
|
| 72 |
+
res = generate_and_post(prompt, caption=None, post=do_post, use_wisdom_as_prompt=use_wisdom, provider_order=provider_order)
|
| 73 |
+
img_path = res.get("image_path")
|
| 74 |
+
wisdom = res.get("wisdom")
|
| 75 |
+
fb = res.get("facebook")
|
| 76 |
+
status_text = "Saved: " + img_path
|
| 77 |
+
if wisdom:
|
| 78 |
+
status_text += " | Wisdom used: " + (wisdom if len(wisdom) < 120 else wisdom[:117] + "...")
|
| 79 |
+
if fb:
|
| 80 |
+
status_text += " | Posted: " + str(fb)
|
| 81 |
+
return img_path, status_text
|
| 82 |
+
except Exception as e:
|
| 83 |
+
return None, "Error: " + str(e)
|
| 84 |
+
|
| 85 |
+
img_btn.click(fn=_gen_img, inputs=[image_prompt, image_post, use_wisdom_for_image, force_replicate], outputs=[img_output, img_status])
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
# Before launching, optionally start the daily Replicate job if enabled
|
| 89 |
+
def validate_tokens() -> bool:
|
| 90 |
+
"""Validate that required tokens are present and usable."""
|
| 91 |
+
load_dotenv()
|
| 92 |
+
fb_token = os.getenv("FB_PAGE_ACCESS_TOKEN")
|
| 93 |
+
fb_page = os.getenv("FB_PAGE_ID")
|
| 94 |
+
rep_token = os.getenv("REPLICATE_API_TOKEN")
|
| 95 |
+
ok = True
|
| 96 |
+
if not fb_token or not fb_page:
|
| 97 |
+
logger.error("Facebook token or page id missing")
|
| 98 |
+
ok = False
|
| 99 |
+
else:
|
| 100 |
+
try:
|
| 101 |
+
r = requests.get(f"https://graph.facebook.com/me?access_token={fb_token}", timeout=10)
|
| 102 |
+
if r.status_code != 200:
|
| 103 |
+
logger.warning("Facebook token validation returned %s: %s", r.status_code, r.text)
|
| 104 |
+
ok = False
|
| 105 |
+
except Exception:
|
| 106 |
+
logger.exception("Facebook token validation failed")
|
| 107 |
+
ok = False
|
| 108 |
+
|
| 109 |
+
if not rep_token:
|
| 110 |
+
logger.error("Replicate token missing")
|
| 111 |
+
ok = False
|
| 112 |
+
else:
|
| 113 |
+
try:
|
| 114 |
+
r2 = requests.get("https://api.replicate.com/v1/models", headers={"Authorization": f"Token {rep_token}"}, timeout=10)
|
| 115 |
+
if r2.status_code not in (200, 401):
|
| 116 |
+
# 401 means token invalid - still a valid response shape
|
| 117 |
+
logger.warning("Replicate models check returned %s", r2.status_code)
|
| 118 |
+
# treat 200 as ok
|
| 119 |
+
if r2.status_code == 200:
|
| 120 |
+
pass
|
| 121 |
+
except Exception:
|
| 122 |
+
logger.exception("Replicate token validation failed")
|
| 123 |
+
ok = False
|
| 124 |
+
|
| 125 |
+
return ok
|
| 126 |
+
|
| 127 |
+
run_daily = os.getenv("RUN_DAILY_REPLICATE", "false").lower() in ("1", "true", "yes")
|
| 128 |
+
if run_daily:
|
| 129 |
+
logger.info("RUN_DAILY_REPLICATE enabled — validating tokens before starting background job")
|
| 130 |
+
if validate_tokens():
|
| 131 |
+
def _bg():
|
| 132 |
+
interval_hours = int(os.getenv("DAILY_INTERVAL_HOURS", "24"))
|
| 133 |
+
while True:
|
| 134 |
+
try:
|
| 135 |
+
logger.info("Starting scheduled daily generate_and_post run")
|
| 136 |
+
# reuse existing generate_and_post helper: generate image (using provider order) and post
|
| 137 |
+
prompt = os.getenv("DAILY_PROMPT")
|
| 138 |
+
if not prompt:
|
| 139 |
+
prompt = '''Create a photorealistic, serene Buddhist scene at sunrise. A calm Buddha statue in side profile, seated in meditation on a stone platform. Soft golden morning light with gentle rim lighting. Misty mountains and ancient Buddhist temple stupas fading into the background, creating depth and a peaceful spiritual atmosphere. Subtle haze, warm earth tones, cinematic lighting, natural stone textures, shallow depth of field. A tranquil lotus flower near still reflective water in the foreground.
|
| 140 |
+
|
| 141 |
+
Generate a short, original Buddhist-style quote about mindfulness, impermanence, inner peace, or awareness. The quote must be calm, timeless, and simple (no modern language, no slang). Keep it under 18 words.
|
| 142 |
+
|
| 143 |
+
Overlay the generated quote text in the center of the image using an elegant serif or handwritten-style font. The text should be softly glowing, perfectly legible, minimal, and harmonious with the scene. Avoid bold, modern, or decorative typography.
|
| 144 |
+
|
| 145 |
+
Ultra-realistic photography style, fine-art cinematic composition, calming mood, high detail, balanced contrast, 4K quality.'''
|
| 146 |
+
try:
|
| 147 |
+
res = generate_and_post(prompt, caption=None, post=True, use_wisdom_as_prompt=True, caption_template=None, use_wisdom_as_caption=True)
|
| 148 |
+
logger.info("Scheduled run result: %s", res)
|
| 149 |
+
except Exception:
|
| 150 |
+
logger.exception("Scheduled run failed")
|
| 151 |
+
except Exception:
|
| 152 |
+
logger.exception("Scheduled background loop crashed")
|
| 153 |
+
logger.info("Sleeping for %s hours before next scheduled run", interval_hours)
|
| 154 |
+
time.sleep(interval_hours * 3600)
|
| 155 |
+
|
| 156 |
+
t = threading.Thread(target=_bg, daemon=True)
|
| 157 |
+
t.start()
|
| 158 |
+
logger.info("Started background daily generate_and_post thread")
|
| 159 |
+
else:
|
| 160 |
+
logger.error("Token validation failed — daily job will not start")
|
| 161 |
+
|
| 162 |
+
demo.launch()
|
check_hf.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import whoami, repo_info
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
import os, json, traceback
|
| 4 |
+
|
| 5 |
+
load_dotenv()
|
| 6 |
+
TOKEN = os.getenv('HF')
|
| 7 |
+
print('HF token present:', bool(TOKEN))
|
| 8 |
+
if not TOKEN:
|
| 9 |
+
print('No HF token found in environment.')
|
| 10 |
+
raise SystemExit(1)
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
info = whoami(token=TOKEN)
|
| 14 |
+
print('whoami:')
|
| 15 |
+
print(json.dumps(info, indent=2))
|
| 16 |
+
except Exception:
|
| 17 |
+
print('whoami error:')
|
| 18 |
+
traceback.print_exc()
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
ri = repo_info('gowshiselva/whispermonk', repo_type='space', token=TOKEN)
|
| 22 |
+
print('repo_info:')
|
| 23 |
+
print(json.dumps(ri.to_dict(), indent=2))
|
| 24 |
+
except Exception:
|
| 25 |
+
print('repo_info error:')
|
| 26 |
+
traceback.print_exc()
|
create_space_and_push.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import subprocess
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
HF_TOKEN = os.getenv("HF") or os.getenv("HUGGINGFACE_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 8 |
+
if not HF_TOKEN:
|
| 9 |
+
print("ERROR: No HF token found in environment (.env). Set HF=<your token>")
|
| 10 |
+
sys.exit(1)
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
ARCHIVED: create_space_and_push.py
|
| 14 |
+
|
| 15 |
+
This helper was useful during initial development but is not required inside
|
| 16 |
+
the Space repository. Kept here as an archive placeholder.
|
| 17 |
+
"""
|
deploy_hf_space.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
except Exception:
|
| 10 |
+
load_dotenv = None
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from huggingface_hub import HfApi
|
| 14 |
+
except Exception:
|
| 15 |
+
HfApi = None
|
| 16 |
+
|
| 17 |
+
ROOT = Path.cwd()
|
| 18 |
+
|
| 19 |
+
def load_token():
|
| 20 |
+
if load_dotenv:
|
| 21 |
+
dotenv_path = ROOT / '.env'
|
| 22 |
+
if dotenv_path.exists():
|
| 23 |
+
load_dotenv(dotenv_path)
|
| 24 |
+
for name in ('HF_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HUGGINGFACE_TOKEN', 'HF'):
|
| 25 |
+
val = os.getenv(name)
|
| 26 |
+
if val:
|
| 27 |
+
return val
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
def run(cmd, check=True):
|
| 31 |
+
print('>', ' '.join(cmd))
|
| 32 |
+
res = subprocess.run(cmd, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
| 33 |
+
print(res.stdout)
|
| 34 |
+
if check and res.returncode != 0:
|
| 35 |
+
raise SystemExit(res.returncode)
|
| 36 |
+
return res
|
| 37 |
+
|
| 38 |
+
def ensure_git_init():
|
| 39 |
+
if not (ROOT / '.git').exists():
|
| 40 |
+
run(['git', 'init'])
|
| 41 |
+
# set main branch
|
| 42 |
+
run(['git', 'branch', '-M', 'main'], check=False)
|
| 43 |
+
# Only add/commit if there are changes
|
| 44 |
+
status = subprocess.run(['git', 'status', '--porcelain'], cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
| 45 |
+
if status.stdout.strip():
|
| 46 |
+
# perform add/commit without capturing stdout to avoid blocking on large outputs/hooks
|
| 47 |
+
print('> git add .')
|
| 48 |
+
subprocess.run(['git', 'add', '.'], cwd=ROOT)
|
| 49 |
+
print('> git commit -m "Initial commit for HF Space"')
|
| 50 |
+
subprocess.run(['git', 'commit', '-m', 'Initial commit for HF Space'], cwd=ROOT)
|
| 51 |
+
|
| 52 |
+
def create_space_and_push(token, repo_name=None, private=False):
|
| 53 |
+
if HfApi is None:
|
| 54 |
+
print('huggingface_hub not installed. Please run: python -m pip install huggingface_hub')
|
| 55 |
+
raise SystemExit(1)
|
| 56 |
+
|
| 57 |
+
api = HfApi()
|
| 58 |
+
who = api.whoami(token=token)
|
| 59 |
+
username = who.get('name') or who.get('user', {}).get('name')
|
| 60 |
+
if not username:
|
| 61 |
+
print('Unable to determine HF username via token.')
|
| 62 |
+
raise SystemExit(1)
|
| 63 |
+
|
| 64 |
+
if repo_name is None:
|
| 65 |
+
repo_name = ROOT.name
|
| 66 |
+
|
| 67 |
+
repo_id = f"{username}/{repo_name}"
|
| 68 |
+
print('Creating or ensuring Space:', repo_id)
|
| 69 |
+
try:
|
| 70 |
+
api.create_repo(repo_id=repo_id, repo_type='space', token=token, private=private, space_sdk='gradio')
|
| 71 |
+
print('Repository created or already exists.')
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print('create_repo warning:', e)
|
| 74 |
+
|
| 75 |
+
# Use huggingface_hub.Repository helper to push with token
|
| 76 |
+
try:
|
| 77 |
+
from huggingface_hub import Repository
|
| 78 |
+
repo_local_dir = str(ROOT)
|
| 79 |
+
print('Using huggingface_hub.Repository to push files (handles auth).')
|
| 80 |
+
repo = Repository(local_dir=repo_local_dir, clone_from=repo_id, use_auth_token=token)
|
| 81 |
+
repo.push_to_hub(commit_message='Initial commit for HF Space')
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print('Repository push via huggingface_hub failed:', e)
|
| 84 |
+
print('Falling back to adding token-embedded remote and git push (may fail if token invalid).')
|
| 85 |
+
remote = f"https://{token}@huggingface.co/spaces/{repo_id}.git"
|
| 86 |
+
# remove existing origin if points elsewhere
|
| 87 |
+
run(['git', 'remote', 'remove', 'origin'], check=False)
|
| 88 |
+
run(['git', 'remote', 'add', 'origin', remote])
|
| 89 |
+
run(['git', 'push', '-u', 'origin', 'main'], check=False)
|
| 90 |
+
|
| 91 |
+
def main():
|
| 92 |
+
token = load_token()
|
| 93 |
+
if not token:
|
| 94 |
+
print('No HF token found in environment or .env. Set HF_TOKEN or HUGGINGFACEHUB_API_TOKEN in .env or env.')
|
| 95 |
+
sys.exit(2)
|
| 96 |
+
|
| 97 |
+
ensure_git_init()
|
| 98 |
+
create_space_and_push(token, repo_name=None, private=False)
|
| 99 |
+
print('\nDeploy complete. Visit your Space URL:')
|
| 100 |
+
time.sleep(0.5)
|
| 101 |
+
print('https://huggingface.co/spaces/{owner}/{repo}'.format(owner=HfApi().whoami(token=token).get('name'), repo=ROOT.name))
|
| 102 |
+
|
| 103 |
+
if __name__ == '__main__':
|
| 104 |
+
main()
|
exchange_tokens.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import requests
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def exchange_short_lived_token(app_id: str, app_secret: str, short_token: str) -> str:
|
| 8 |
+
url = "https://graph.facebook.com/v15.0/oauth/access_token"
|
| 9 |
+
params = {
|
| 10 |
+
"grant_type": "fb_exchange_token",
|
| 11 |
+
"client_id": app_id,
|
| 12 |
+
"client_secret": app_secret,
|
| 13 |
+
"fb_exchange_token": short_token,
|
| 14 |
+
}
|
| 15 |
+
r = requests.get(url, params=params)
|
| 16 |
+
r.raise_for_status()
|
| 17 |
+
data = r.json()
|
| 18 |
+
return data.get("access_token")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def debug_token(app_id: str, app_secret: str, token: str) -> dict:
|
| 22 |
+
# uses the app access token (app_id|app_secret)
|
| 23 |
+
app_access = f"{app_id}|{app_secret}"
|
| 24 |
+
url = "https://graph.facebook.com/debug_token"
|
| 25 |
+
params = {"input_token": token, "access_token": app_access}
|
| 26 |
+
r = requests.get(url, params=params)
|
| 27 |
+
r.raise_for_status()
|
| 28 |
+
return r.json()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_page_access_token(long_lived_user_token: str, page_id: str | None = None, page_name: str | None = None):
|
| 32 |
+
url = "https://graph.facebook.com/v15.0/me/accounts"
|
| 33 |
+
params = {"access_token": long_lived_user_token}
|
| 34 |
+
r = requests.get(url, params=params)
|
| 35 |
+
r.raise_for_status()
|
| 36 |
+
data = r.json().get("data", [])
|
| 37 |
+
for page in data:
|
| 38 |
+
if page_id and str(page.get("id")) == str(page_id):
|
| 39 |
+
return page.get("access_token"), page
|
| 40 |
+
if page_name and page.get("name") and page_name.lower() in page.get("name").lower():
|
| 41 |
+
return page.get("access_token"), page
|
| 42 |
+
return None, None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def write_env_token(env_path: str, token: str):
|
| 46 |
+
# simple replacement or append
|
| 47 |
+
if not os.path.exists(env_path):
|
| 48 |
+
with open(env_path, "w", encoding="utf-8") as f:
|
| 49 |
+
f.write(f"FB_PAGE_ACCESS_TOKEN={token}\n")
|
| 50 |
+
return
|
| 51 |
+
|
| 52 |
+
with open(env_path, "r", encoding="utf-8") as f:
|
| 53 |
+
lines = f.readlines()
|
| 54 |
+
|
| 55 |
+
key = "FB_PAGE_ACCESS_TOKEN"
|
| 56 |
+
found = False
|
| 57 |
+
for i, ln in enumerate(lines):
|
| 58 |
+
if ln.strip().startswith(key + "="):
|
| 59 |
+
lines[i] = f"{key}={token}\n"
|
| 60 |
+
found = True
|
| 61 |
+
break
|
| 62 |
+
|
| 63 |
+
if not found:
|
| 64 |
+
# append
|
| 65 |
+
if not lines or not lines[-1].endswith("\n"):
|
| 66 |
+
lines.append("\n")
|
| 67 |
+
lines.append(f"{key}={token}\n")
|
| 68 |
+
|
| 69 |
+
# write backup then replace
|
| 70 |
+
bak = env_path + ".bak"
|
| 71 |
+
try:
|
| 72 |
+
if os.path.exists(env_path):
|
| 73 |
+
os.replace(env_path, bak)
|
| 74 |
+
with open(env_path, "w", encoding="utf-8") as f:
|
| 75 |
+
f.writelines(lines)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
# attempt to restore
|
| 78 |
+
if os.path.exists(bak):
|
| 79 |
+
os.replace(bak, env_path)
|
| 80 |
+
raise e
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
env_path = os.path.join(os.getcwd(), ".env")
|
| 85 |
+
# ensure we explicitly load the project's .env file
|
| 86 |
+
load_dotenv(env_path)
|
| 87 |
+
|
| 88 |
+
app_id = os.getenv("FB_APP_ID")
|
| 89 |
+
app_secret = os.getenv("FB_APP_SECRET")
|
| 90 |
+
page_id = os.getenv("FB_PAGE_ID")
|
| 91 |
+
page_name = os.getenv("FB_PAGE_NAME") or "whisper monk"
|
| 92 |
+
# accept a few possible env var names (typos included)
|
| 93 |
+
short_token = (
|
| 94 |
+
os.getenv("FB_USER_SHORT_TOKEN")
|
| 95 |
+
or os.getenv("FB_USER_TOKEN")
|
| 96 |
+
or os.getenv("FB_USER_TOEK")
|
| 97 |
+
or os.getenv("FB_USER_TOEKN")
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if not app_id or not app_secret:
|
| 101 |
+
print("ERROR: FB_APP_ID and FB_APP_SECRET must be set in .env")
|
| 102 |
+
sys.exit(1)
|
| 103 |
+
|
| 104 |
+
if not short_token:
|
| 105 |
+
print("ERROR: No user token found in .env (FB_USER_SHORT_TOKEN or FB_USER_TOKEN).")
|
| 106 |
+
sys.exit(1)
|
| 107 |
+
|
| 108 |
+
# First, inspect the token. If it's already a Page token, accept it directly.
|
| 109 |
+
try:
|
| 110 |
+
dbg = debug_token(app_id, app_secret, short_token)
|
| 111 |
+
except requests.HTTPError as e:
|
| 112 |
+
print("Token debug failed — attempting direct page lookup with provided token...")
|
| 113 |
+
try:
|
| 114 |
+
page_token, page_info = get_page_access_token(short_token, page_id=page_id, page_name=page_name)
|
| 115 |
+
except requests.HTTPError as e2:
|
| 116 |
+
print("Direct page lookup failed:", e2.response.text if e2.response is not None else str(e2))
|
| 117 |
+
sys.exit(1)
|
| 118 |
+
if page_token:
|
| 119 |
+
print("Found page using the provided token:", page_info.get("name"))
|
| 120 |
+
write_env_token(env_path, page_token)
|
| 121 |
+
print(f"Wrote FB_PAGE_ACCESS_TOKEN to {env_path}")
|
| 122 |
+
return
|
| 123 |
+
print("No page found via direct lookup; giving up.")
|
| 124 |
+
sys.exit(1)
|
| 125 |
+
|
| 126 |
+
data = dbg.get("data", {})
|
| 127 |
+
token_type = data.get("type")
|
| 128 |
+
if token_type and token_type.upper() == "PAGE":
|
| 129 |
+
print("Token is already a Page token — writing directly to .env")
|
| 130 |
+
write_env_token(env_path, short_token)
|
| 131 |
+
print(f"Wrote FB_PAGE_ACCESS_TOKEN to {env_path}")
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
print("Exchanging short-lived user token for long-lived token...")
|
| 135 |
+
try:
|
| 136 |
+
long_lived = exchange_short_lived_token(app_id, app_secret, short_token)
|
| 137 |
+
except requests.HTTPError as e:
|
| 138 |
+
print("Token exchange failed:", e.response.text if e.response is not None else str(e))
|
| 139 |
+
sys.exit(1)
|
| 140 |
+
|
| 141 |
+
if not long_lived:
|
| 142 |
+
print("Failed to obtain long-lived user token")
|
| 143 |
+
sys.exit(1)
|
| 144 |
+
|
| 145 |
+
print("Long-lived user token obtained.")
|
| 146 |
+
print("Retrieving managed pages for the user...")
|
| 147 |
+
try:
|
| 148 |
+
page_token, page_info = get_page_access_token(long_lived, page_id=page_id, page_name=page_name)
|
| 149 |
+
except requests.HTTPError as e:
|
| 150 |
+
print("Failed to list pages:", e.response.text if e.response is not None else str(e))
|
| 151 |
+
sys.exit(1)
|
| 152 |
+
|
| 153 |
+
if not page_token:
|
| 154 |
+
print("No matching page found for", page_id or page_name)
|
| 155 |
+
sys.exit(1)
|
| 156 |
+
|
| 157 |
+
print("Found page:", page_info.get("name"), "(id:", page_info.get("id"), ")")
|
| 158 |
+
print("Page access token retrieved.")
|
| 159 |
+
|
| 160 |
+
# write into .env
|
| 161 |
+
write_env_token(env_path, page_token)
|
| 162 |
+
print(f"Wrote FB_PAGE_ACCESS_TOKEN to {env_path} (previous saved as {env_path}.bak)")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
main()
|
generate_image.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import base64
|
| 4 |
+
import logging
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
from generate_wisdom import generate_wisdom
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from openai import OpenAI
|
| 10 |
+
openai_client = OpenAI()
|
| 11 |
+
openai_legacy = None
|
| 12 |
+
except Exception:
|
| 13 |
+
try:
|
| 14 |
+
import openai as openai_legacy
|
| 15 |
+
openai_client = None
|
| 16 |
+
except Exception:
|
| 17 |
+
openai_client = None
|
| 18 |
+
openai_legacy = None
|
| 19 |
+
|
| 20 |
+
import requests
|
| 21 |
+
|
| 22 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def generate_image_hf(prompt: str, model: str = "stabilityai/stable-diffusion-2", size: str = "1024x1024", steps: int = 20, guidance: float = 7.5) -> bytes:
|
| 27 |
+
"""Generate image bytes using Hugging Face Inference API as a fallback.
|
| 28 |
+
|
| 29 |
+
Tries the requested `model` first; if it's not available via the Inference API
|
| 30 |
+
(HTTP 410/404) the function will try a small list of common SD models.
|
| 31 |
+
"""
|
| 32 |
+
load_dotenv()
|
| 33 |
+
hf_token = os.getenv("HF")
|
| 34 |
+
if not hf_token:
|
| 35 |
+
logger.error("HF token missing in environment (HF)")
|
| 36 |
+
raise RuntimeError("HF token missing in environment (HF)")
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
width, height = (int(x) for x in size.split("x"))
|
| 40 |
+
except Exception:
|
| 41 |
+
width, height = 1024, 1024
|
| 42 |
+
|
| 43 |
+
candidate_models = [model, "runwayml/stable-diffusion-v1-5", "prompthero/openjourney"]
|
| 44 |
+
last_exc = None
|
| 45 |
+
for m in candidate_models:
|
| 46 |
+
url = f"https://api-inference.huggingface.co/models/{m}"
|
| 47 |
+
headers = {"Authorization": f"Bearer {hf_token}", "Accept": "application/json"}
|
| 48 |
+
payload = {
|
| 49 |
+
"inputs": prompt,
|
| 50 |
+
"parameters": {
|
| 51 |
+
"width": width,
|
| 52 |
+
"height": height,
|
| 53 |
+
"num_inference_steps": steps,
|
| 54 |
+
"guidance_scale": guidance,
|
| 55 |
+
},
|
| 56 |
+
"options": {"wait_for_model": True},
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
logger.info("Trying HF model %s (size=%sx%s, steps=%s)", m, width, height, steps)
|
| 60 |
+
try:
|
| 61 |
+
resp = requests.post(url, headers=headers, json=payload, timeout=120)
|
| 62 |
+
resp.raise_for_status()
|
| 63 |
+
except requests.HTTPError as e:
|
| 64 |
+
status = getattr(e.response, "status_code", None)
|
| 65 |
+
logger.warning("HF model %s returned HTTP %s", m, status)
|
| 66 |
+
last_exc = e
|
| 67 |
+
# try next candidate if model not hosted on inference API (410/Gone or 404)
|
| 68 |
+
if status in (404, 410):
|
| 69 |
+
# attempt Space /api/predict for public Spaces (owner/model -> /spaces/owner/model)
|
| 70 |
+
try:
|
| 71 |
+
owner, repo = m.split("/", 1)
|
| 72 |
+
space_url = f"https://huggingface.co/spaces/{owner}/{repo}/api/predict"
|
| 73 |
+
logger.info("Trying Space API %s", space_url)
|
| 74 |
+
sp_headers = {"Authorization": f"Bearer {hf_token}"} if hf_token else {}
|
| 75 |
+
sp_payload = {"data": [prompt]}
|
| 76 |
+
sp_resp = requests.post(space_url, headers=sp_headers, json=sp_payload, timeout=180)
|
| 77 |
+
sp_resp.raise_for_status()
|
| 78 |
+
js = sp_resp.json()
|
| 79 |
+
# many Spaces return {'data': [...]} where the first item is base64 or url
|
| 80 |
+
if isinstance(js, dict) and "data" in js:
|
| 81 |
+
first = js["data"][0]
|
| 82 |
+
if isinstance(first, str):
|
| 83 |
+
# try base64 decode
|
| 84 |
+
import re
|
| 85 |
+
|
| 86 |
+
mobj = re.search(r"([A-Za-z0-9+/=]{200,})", first)
|
| 87 |
+
if mobj:
|
| 88 |
+
return base64.b64decode(mobj.group(1))
|
| 89 |
+
# if it's a direct URL, try fetching bytes
|
| 90 |
+
if first.startswith("http"):
|
| 91 |
+
r2 = requests.get(first, timeout=60)
|
| 92 |
+
r2.raise_for_status()
|
| 93 |
+
return r2.content
|
| 94 |
+
# if we reach here, the Space didn't return usable image; continue to next model
|
| 95 |
+
except Exception:
|
| 96 |
+
logger.warning("Space API attempt for %s failed", m)
|
| 97 |
+
continue
|
| 98 |
+
raise
|
| 99 |
+
|
| 100 |
+
content_type = resp.headers.get("content-type", "")
|
| 101 |
+
if content_type.startswith("application/json"):
|
| 102 |
+
js = resp.json()
|
| 103 |
+
# Try common response shapes for base64-encoded image
|
| 104 |
+
b64 = None
|
| 105 |
+
if isinstance(js, dict):
|
| 106 |
+
for key in ("image", "generated_image", "data", "images"):
|
| 107 |
+
if key in js:
|
| 108 |
+
val = js[key]
|
| 109 |
+
if isinstance(val, str):
|
| 110 |
+
b64 = val
|
| 111 |
+
break
|
| 112 |
+
if isinstance(val, list) and val:
|
| 113 |
+
first = val[0]
|
| 114 |
+
if isinstance(first, dict) and "image_base64" in first:
|
| 115 |
+
b64 = first["image_base64"]
|
| 116 |
+
break
|
| 117 |
+
if isinstance(first, str):
|
| 118 |
+
b64 = first
|
| 119 |
+
break
|
| 120 |
+
if not b64:
|
| 121 |
+
import re
|
| 122 |
+
|
| 123 |
+
txt = str(js)
|
| 124 |
+
mobj = re.search(r"([A-Za-z0-9+/=]{200,})", txt)
|
| 125 |
+
if mobj:
|
| 126 |
+
b64 = mobj.group(1)
|
| 127 |
+
if not b64:
|
| 128 |
+
raise RuntimeError("No base64 image found in HF JSON response")
|
| 129 |
+
return base64.b64decode(b64)
|
| 130 |
+
|
| 131 |
+
# otherwise assume binary image content
|
| 132 |
+
return resp.content
|
| 133 |
+
|
| 134 |
+
# If loop exhausted, raise last exception
|
| 135 |
+
if last_exc:
|
| 136 |
+
raise last_exc
|
| 137 |
+
raise RuntimeError("Hugging Face image generation failed for all candidates")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def generate_image_replicate(prompt: str, model: str | None = None, image_inputs: list | None = None, aspect_ratio: str = "match_input_image", output_format: str = "jpg") -> bytes:
|
| 141 |
+
"""Generate image bytes using Replicate as a final fallback.
|
| 142 |
+
|
| 143 |
+
Requires `REPLICATE_API_TOKEN` in the environment.
|
| 144 |
+
"""
|
| 145 |
+
load_dotenv()
|
| 146 |
+
token = os.getenv("REPLICATE_API_TOKEN")
|
| 147 |
+
if not token:
|
| 148 |
+
logger.error("REPLICATE_API_TOKEN missing in environment")
|
| 149 |
+
raise RuntimeError("REPLICATE_API_TOKEN missing in environment")
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
import replicate
|
| 153 |
+
except Exception:
|
| 154 |
+
logger.exception("Replicate client not installed")
|
| 155 |
+
raise
|
| 156 |
+
|
| 157 |
+
# Build list of replicate model candidates: primary then alternates
|
| 158 |
+
if model is None:
|
| 159 |
+
primary = os.getenv("REPLICATE_MODEL")
|
| 160 |
+
else:
|
| 161 |
+
primary = model
|
| 162 |
+
alternates = os.getenv("REPLICATE_MODEL_ALTERNATES", "")
|
| 163 |
+
candidates = []
|
| 164 |
+
if primary:
|
| 165 |
+
candidates.append(primary)
|
| 166 |
+
if alternates:
|
| 167 |
+
for part in alternates.split(","):
|
| 168 |
+
part = part.strip()
|
| 169 |
+
if part and part not in candidates:
|
| 170 |
+
candidates.append(part)
|
| 171 |
+
|
| 172 |
+
if not candidates:
|
| 173 |
+
logger.error("No Replicate model configured (set REPLICATE_MODEL or REPLICATE_MODEL_ALTERNATES)")
|
| 174 |
+
raise RuntimeError("No Replicate model configured")
|
| 175 |
+
|
| 176 |
+
input_payload = {
|
| 177 |
+
"prompt": prompt,
|
| 178 |
+
"image_input": image_inputs or [],
|
| 179 |
+
"aspect_ratio": aspect_ratio,
|
| 180 |
+
"output_format": output_format,
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
last_exc = None
|
| 184 |
+
for cand in candidates:
|
| 185 |
+
logger.info("Calling Replicate candidate model %s", cand)
|
| 186 |
+
try:
|
| 187 |
+
output = replicate.run(cand, input=input_payload)
|
| 188 |
+
# if succeed, proceed to handle output
|
| 189 |
+
break
|
| 190 |
+
except Exception as e:
|
| 191 |
+
logger.warning("Replicate model %s failed: %s", cand, e)
|
| 192 |
+
last_exc = e
|
| 193 |
+
output = None
|
| 194 |
+
continue
|
| 195 |
+
if output is None:
|
| 196 |
+
logger.error("All Replicate candidates failed")
|
| 197 |
+
raise last_exc or RuntimeError("Replicate generation failed for all candidates")
|
| 198 |
+
|
| 199 |
+
# Replicate often returns a URL or a list of URLs
|
| 200 |
+
logger.info("Replicate output type: %s", type(output))
|
| 201 |
+
# handle common output shapes
|
| 202 |
+
if isinstance(output, str) and output.startswith("http"):
|
| 203 |
+
r = requests.get(output, timeout=120)
|
| 204 |
+
r.raise_for_status()
|
| 205 |
+
return r.content
|
| 206 |
+
if isinstance(output, list) and output:
|
| 207 |
+
first = output[0]
|
| 208 |
+
if isinstance(first, str) and first.startswith("http"):
|
| 209 |
+
r = requests.get(first, timeout=120)
|
| 210 |
+
r.raise_for_status()
|
| 211 |
+
return r.content
|
| 212 |
+
if isinstance(first, bytes):
|
| 213 |
+
return first
|
| 214 |
+
if isinstance(output, bytes):
|
| 215 |
+
return output
|
| 216 |
+
if isinstance(output, dict):
|
| 217 |
+
# try common fields
|
| 218 |
+
if "url" in output and isinstance(output["url"], str):
|
| 219 |
+
r = requests.get(output["url"], timeout=120)
|
| 220 |
+
r.raise_for_status()
|
| 221 |
+
return r.content
|
| 222 |
+
if "image" in output and isinstance(output["image"], str):
|
| 223 |
+
try:
|
| 224 |
+
return base64.b64decode(output["image"])
|
| 225 |
+
except Exception:
|
| 226 |
+
pass
|
| 227 |
+
|
| 228 |
+
raise RuntimeError("Unknown Replicate output format")
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def generate_image_replicate_poll(prompt: str, model: str | None = None, image_inputs: list | None = None, aspect_ratio: str = "match_input_image", output_format: str = "jpg", check_interval: int = 8, timeout: int = 600) -> bytes:
|
| 232 |
+
"""Create a Replicate prediction and poll every `check_interval` seconds until finished.
|
| 233 |
+
|
| 234 |
+
Saves logs and returns raw image bytes when available. Requires `REPLICATE_API_TOKEN` and
|
| 235 |
+
`REPLICATE_MODEL` (or pass `model` param) to be set.
|
| 236 |
+
"""
|
| 237 |
+
load_dotenv()
|
| 238 |
+
token = os.getenv("REPLICATE_API_TOKEN")
|
| 239 |
+
if not token:
|
| 240 |
+
logger.error("REPLICATE_API_TOKEN missing in environment")
|
| 241 |
+
raise RuntimeError("REPLICATE_API_TOKEN missing in environment")
|
| 242 |
+
|
| 243 |
+
# Build candidate list (primary then alternates)
|
| 244 |
+
if model is None:
|
| 245 |
+
primary = os.getenv("REPLICATE_MODEL")
|
| 246 |
+
else:
|
| 247 |
+
primary = model
|
| 248 |
+
alternates = os.getenv("REPLICATE_MODEL_ALTERNATES", "")
|
| 249 |
+
candidates = []
|
| 250 |
+
if primary:
|
| 251 |
+
candidates.append(primary)
|
| 252 |
+
if alternates:
|
| 253 |
+
for part in alternates.split(","):
|
| 254 |
+
part = part.strip()
|
| 255 |
+
if part and part not in candidates:
|
| 256 |
+
candidates.append(part)
|
| 257 |
+
|
| 258 |
+
if not candidates:
|
| 259 |
+
logger.error("No Replicate model configured (set REPLICATE_MODEL or REPLICATE_MODEL_ALTERNATES)")
|
| 260 |
+
raise RuntimeError("No Replicate model configured (REPLICATE_MODEL missing)")
|
| 261 |
+
|
| 262 |
+
url = "https://api.replicate.com/v1/predictions"
|
| 263 |
+
headers = {
|
| 264 |
+
"Authorization": f"Token {token}",
|
| 265 |
+
"Content-Type": "application/json",
|
| 266 |
+
"Accept": "application/json",
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
payload = {
|
| 270 |
+
"version": model,
|
| 271 |
+
"input": {
|
| 272 |
+
"prompt": prompt,
|
| 273 |
+
"image_input": image_inputs or [],
|
| 274 |
+
"aspect_ratio": aspect_ratio,
|
| 275 |
+
"output_format": output_format,
|
| 276 |
+
},
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
last_exc = None
|
| 280 |
+
for cand in candidates:
|
| 281 |
+
logger.info("Creating Replicate prediction for model %s", cand)
|
| 282 |
+
payload["version"] = cand
|
| 283 |
+
try:
|
| 284 |
+
resp = requests.post(url, headers=headers, json=payload, timeout=30)
|
| 285 |
+
resp.raise_for_status()
|
| 286 |
+
except Exception as e:
|
| 287 |
+
logger.warning("Replicate create failed for %s: %s", cand, e)
|
| 288 |
+
last_exc = e
|
| 289 |
+
continue
|
| 290 |
+
pred = resp.json()
|
| 291 |
+
pred_id = pred.get("id")
|
| 292 |
+
if not pred_id:
|
| 293 |
+
logger.warning("Replicate create returned no id for %s", cand)
|
| 294 |
+
last_exc = RuntimeError("Replicate did not return a prediction id")
|
| 295 |
+
continue
|
| 296 |
+
|
| 297 |
+
logger.info("Replicate prediction created: %s (model=%s)", pred_id, cand)
|
| 298 |
+
started = time.time()
|
| 299 |
+
status = pred.get("status")
|
| 300 |
+
while status in ("starting", "processing", "queued"):
|
| 301 |
+
if time.time() - started > timeout:
|
| 302 |
+
last_exc = RuntimeError("Replicate prediction timed out")
|
| 303 |
+
break
|
| 304 |
+
logger.info("Prediction %s status=%s — sleeping %ss", pred_id, status, check_interval)
|
| 305 |
+
time.sleep(check_interval)
|
| 306 |
+
r2 = requests.get(f"{url}/{pred_id}", headers=headers, timeout=30)
|
| 307 |
+
r2.raise_for_status()
|
| 308 |
+
pred = r2.json()
|
| 309 |
+
status = pred.get("status")
|
| 310 |
+
|
| 311 |
+
if status != "succeeded":
|
| 312 |
+
detail = pred.get("error") or pred.get("output")
|
| 313 |
+
logger.warning("Prediction %s failed with status=%s: %s", pred_id, status, detail)
|
| 314 |
+
last_exc = RuntimeError(f"Replicate prediction failed: {detail}")
|
| 315 |
+
continue
|
| 316 |
+
|
| 317 |
+
logger.info("Prediction %s succeeded (model=%s)", pred_id, cand)
|
| 318 |
+
output = pred.get("output")
|
| 319 |
+
# output is commonly a list of urls
|
| 320 |
+
if isinstance(output, list) and output:
|
| 321 |
+
first = output[0]
|
| 322 |
+
if isinstance(first, str) and first.startswith("http"):
|
| 323 |
+
logger.info("Downloading output from %s", first)
|
| 324 |
+
r3 = requests.get(first, timeout=120)
|
| 325 |
+
r3.raise_for_status()
|
| 326 |
+
return r3.content
|
| 327 |
+
if isinstance(first, bytes):
|
| 328 |
+
return first
|
| 329 |
+
|
| 330 |
+
if isinstance(output, str) and output.startswith("http"):
|
| 331 |
+
r3 = requests.get(output, timeout=120)
|
| 332 |
+
r3.raise_for_status()
|
| 333 |
+
return r3.content
|
| 334 |
+
|
| 335 |
+
# fallback: try to inspect nested structures
|
| 336 |
+
if isinstance(output, dict):
|
| 337 |
+
for k in ("image", "url", "output"):
|
| 338 |
+
v = output.get(k)
|
| 339 |
+
if isinstance(v, str) and v.startswith("http"):
|
| 340 |
+
r3 = requests.get(v, timeout=120)
|
| 341 |
+
r3.raise_for_status()
|
| 342 |
+
return r3.content
|
| 343 |
+
|
| 344 |
+
raise RuntimeError("Unknown Replicate prediction output format")
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def generate_image(prompt: str, size: str = "1024x1024", provider_order: str | None = None) -> str:
|
| 348 |
+
"""Generate an image from `prompt`. Returns local path to saved image (PNG).
|
| 349 |
+
|
| 350 |
+
Behavior: tries providers in the order specified by the `PROVIDER_ORDER`
|
| 351 |
+
environment variable (comma-separated). Supported providers: `openai`,
|
| 352 |
+
`huggingface` (or `hf`), and `replicate`. If a provider fails, the code
|
| 353 |
+
moves to the next provider. Default: `openai,replicate`.
|
| 354 |
+
"""
|
| 355 |
+
load_dotenv()
|
| 356 |
+
logger.info("Generating image for prompt: %s", prompt)
|
| 357 |
+
|
| 358 |
+
def generate_image_openai(local_prompt: str, local_size: str) -> bytes:
|
| 359 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 360 |
+
if not api_key:
|
| 361 |
+
logger.error("OPENAI_API_KEY not set")
|
| 362 |
+
raise RuntimeError("OPENAI_API_KEY not set")
|
| 363 |
+
if openai_client is not None:
|
| 364 |
+
resp = openai_client.images.generate(model="gpt-image-1", prompt=local_prompt, size=local_size)
|
| 365 |
+
b64 = resp.data[0].b64_json
|
| 366 |
+
return base64.b64decode(b64)
|
| 367 |
+
elif openai_legacy is not None:
|
| 368 |
+
openai_legacy.api_key = api_key
|
| 369 |
+
resp = openai_legacy.Image.create(prompt=local_prompt, size=local_size, n=1)
|
| 370 |
+
b64 = resp["data"][0]["b64_json"]
|
| 371 |
+
return base64.b64decode(b64)
|
| 372 |
+
else:
|
| 373 |
+
raise RuntimeError("No OpenAI client available")
|
| 374 |
+
|
| 375 |
+
# Provider order from env, default to openai then replicate
|
| 376 |
+
if provider_order is None:
|
| 377 |
+
provider_order = os.getenv("PROVIDER_ORDER", "openai,replicate")
|
| 378 |
+
providers = [p.strip().lower() for p in provider_order.split(",") if p.strip()]
|
| 379 |
+
if not providers:
|
| 380 |
+
providers = ["openai", "replicate"]
|
| 381 |
+
|
| 382 |
+
img_bytes = None
|
| 383 |
+
last_exc = None
|
| 384 |
+
for provider in providers:
|
| 385 |
+
try:
|
| 386 |
+
logger.info("Trying provider: %s", provider)
|
| 387 |
+
if provider in ("openai", "oa"):
|
| 388 |
+
img_bytes = generate_image_openai(prompt, size)
|
| 389 |
+
elif provider in ("huggingface", "hf"):
|
| 390 |
+
img_bytes = generate_image_hf(prompt, size=size)
|
| 391 |
+
elif provider == "replicate":
|
| 392 |
+
# use polling replicate fallback (checks every 8s)
|
| 393 |
+
img_bytes = generate_image_replicate_poll(prompt, check_interval=8)
|
| 394 |
+
else:
|
| 395 |
+
logger.warning("Unknown provider '%s' — skipping", provider)
|
| 396 |
+
continue
|
| 397 |
+
# if generation succeeded, break loop
|
| 398 |
+
if img_bytes:
|
| 399 |
+
logger.info("Provider %s succeeded", provider)
|
| 400 |
+
break
|
| 401 |
+
except Exception as e:
|
| 402 |
+
logger.exception("Provider %s failed: %s", provider, e)
|
| 403 |
+
last_exc = e
|
| 404 |
+
continue
|
| 405 |
+
|
| 406 |
+
if not img_bytes:
|
| 407 |
+
logger.error("All providers failed")
|
| 408 |
+
if last_exc:
|
| 409 |
+
raise SystemExit(1) from last_exc
|
| 410 |
+
raise SystemExit(1)
|
| 411 |
+
out_dir = os.path.join(os.getcwd(), "generated_images")
|
| 412 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 413 |
+
ts = int(time.time())
|
| 414 |
+
filename = f"image_{ts}.png"
|
| 415 |
+
path = os.path.join(out_dir, filename)
|
| 416 |
+
with open(path, "wb") as f:
|
| 417 |
+
f.write(img_bytes)
|
| 418 |
+
|
| 419 |
+
logger.info("Saved generated image to %s", path)
|
| 420 |
+
return path
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def post_image_to_facebook(page_id: str, access_token: str, image_path: str, caption: str | None = None) -> dict:
|
| 424 |
+
url = f"https://graph.facebook.com/{page_id}/photos"
|
| 425 |
+
data = {"access_token": access_token}
|
| 426 |
+
if caption:
|
| 427 |
+
data["caption"] = caption
|
| 428 |
+
logger.info("Uploading image %s to Facebook page %s", image_path, page_id)
|
| 429 |
+
with open(image_path, "rb") as imgf:
|
| 430 |
+
files = {"source": imgf}
|
| 431 |
+
resp = requests.post(url, files=files, data=data)
|
| 432 |
+
try:
|
| 433 |
+
resp.raise_for_status()
|
| 434 |
+
except requests.HTTPError:
|
| 435 |
+
logger.error("Facebook upload error: %s", resp.text)
|
| 436 |
+
raise
|
| 437 |
+
logger.info("Upload successful: %s", resp.json())
|
| 438 |
+
return resp.json()
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def generate_and_post(prompt: str, caption: str | None = None, post: bool = False, use_wisdom_as_prompt: bool = False, caption_template: str | None = None, use_wisdom_as_caption: bool = False, provider_order: str | None = None) -> dict:
|
| 442 |
+
# If requested, generate a short wisdom text and use it (or append) as the image prompt
|
| 443 |
+
image_prompt = prompt
|
| 444 |
+
wisdom_text = None
|
| 445 |
+
if use_wisdom_as_prompt:
|
| 446 |
+
try:
|
| 447 |
+
wisdom_text = generate_wisdom(prompt)
|
| 448 |
+
# If no explicit prompt provided, use the wisdom as the image prompt
|
| 449 |
+
if not image_prompt:
|
| 450 |
+
image_prompt = wisdom_text
|
| 451 |
+
else:
|
| 452 |
+
# combine both: image prompt + the wisdom quote to guide imagery
|
| 453 |
+
image_prompt = f"{image_prompt}. Quote: {wisdom_text}"
|
| 454 |
+
except Exception as e:
|
| 455 |
+
logger.exception("Failed to generate wisdom for image prompt: %s", e)
|
| 456 |
+
# proceed using the original prompt
|
| 457 |
+
|
| 458 |
+
img_path = generate_image(image_prompt, provider_order=provider_order)
|
| 459 |
+
result = {"image_path": img_path}
|
| 460 |
+
if wisdom_text:
|
| 461 |
+
result["wisdom"] = wisdom_text
|
| 462 |
+
if post:
|
| 463 |
+
load_dotenv()
|
| 464 |
+
page_id = os.getenv("FB_PAGE_ID")
|
| 465 |
+
token = os.getenv("FB_PAGE_ACCESS_TOKEN")
|
| 466 |
+
if not page_id or not token:
|
| 467 |
+
logger.error("Missing FB_PAGE_ID or FB_PAGE_ACCESS_TOKEN in environment")
|
| 468 |
+
raise SystemExit(1)
|
| 469 |
+
|
| 470 |
+
# build final caption: explicit caption wins; then caption_template; then wisdom if requested
|
| 471 |
+
final_caption = caption
|
| 472 |
+
if not final_caption and caption_template:
|
| 473 |
+
try:
|
| 474 |
+
final_caption = caption_template.format(prompt=prompt or "", wisdom=wisdom_text or "")
|
| 475 |
+
except Exception:
|
| 476 |
+
logger.exception("Failed to format caption_template")
|
| 477 |
+
final_caption = caption_template
|
| 478 |
+
if not final_caption and use_wisdom_as_caption and wisdom_text:
|
| 479 |
+
final_caption = wisdom_text
|
| 480 |
+
|
| 481 |
+
res = post_image_to_facebook(page_id, token, img_path, final_caption)
|
| 482 |
+
result["facebook"] = res
|
| 483 |
+
return result
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
if __name__ == "__main__":
|
| 487 |
+
import argparse
|
| 488 |
+
|
| 489 |
+
parser = argparse.ArgumentParser(description="Generate an image via OpenAI and optionally post to Facebook")
|
| 490 |
+
parser.add_argument("-p", "--prompt", required=True, help="Prompt for image generation")
|
| 491 |
+
parser.add_argument("--caption", help="Caption to use when posting to Facebook")
|
| 492 |
+
parser.add_argument("--caption-template", help="Caption template, supports {prompt} and {wisdom}")
|
| 493 |
+
parser.add_argument("--use-wisdom-as-caption", action="store_true", help="Use generated wisdom as caption if available")
|
| 494 |
+
parser.add_argument("--post", action="store_true", help="Post image to Facebook after generation")
|
| 495 |
+
args = parser.parse_args()
|
| 496 |
+
|
| 497 |
+
res = generate_and_post(
|
| 498 |
+
args.prompt,
|
| 499 |
+
caption=args.caption,
|
| 500 |
+
post=args.post,
|
| 501 |
+
caption_template=args.caption_template,
|
| 502 |
+
use_wisdom_as_caption=args.use_wisdom_as_caption,
|
| 503 |
+
)
|
| 504 |
+
print(res)
|
generate_wisdom.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import argparse
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
# new OpenAI v1 client
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
openai_client = OpenAI()
|
| 10 |
+
openai_legacy = None
|
| 11 |
+
except Exception:
|
| 12 |
+
try:
|
| 13 |
+
import openai as openai_legacy
|
| 14 |
+
openai_client = None
|
| 15 |
+
except Exception:
|
| 16 |
+
openai_client = None
|
| 17 |
+
openai_legacy = None
|
| 18 |
+
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def generate_wisdom(prompt: str | None = None, max_tokens: int = 120) -> str:
|
| 24 |
+
load_dotenv()
|
| 25 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 26 |
+
if not api_key:
|
| 27 |
+
logger.error("OPENAI_API_KEY not found in environment")
|
| 28 |
+
raise SystemExit(1)
|
| 29 |
+
|
| 30 |
+
base_prompt = (
|
| 31 |
+
"You are a concise Buddhist teacher. Provide a short (1-3 sentence) piece of wisdom"
|
| 32 |
+
" suitable for a social media post. Keep it insightful, non-denominational, and respectful."
|
| 33 |
+
)
|
| 34 |
+
if prompt:
|
| 35 |
+
user_prompt = f"{base_prompt}\nTopic: {prompt}\n"
|
| 36 |
+
else:
|
| 37 |
+
user_prompt = base_prompt
|
| 38 |
+
|
| 39 |
+
logger.info("Requesting wisdom from OpenAI (max_tokens=%s)", max_tokens)
|
| 40 |
+
|
| 41 |
+
if openai_client is not None:
|
| 42 |
+
# new OpenAI v1 client
|
| 43 |
+
resp = openai_client.chat.completions.create(
|
| 44 |
+
model="gpt-3.5-turbo",
|
| 45 |
+
messages=[
|
| 46 |
+
{"role": "system", "content": "You generate short Buddhist wisdom quotes."},
|
| 47 |
+
{"role": "user", "content": user_prompt},
|
| 48 |
+
],
|
| 49 |
+
max_tokens=max_tokens,
|
| 50 |
+
temperature=0.8,
|
| 51 |
+
)
|
| 52 |
+
# response shape: resp.choices[0].message.content
|
| 53 |
+
try:
|
| 54 |
+
text = resp.choices[0].message.content.strip()
|
| 55 |
+
except Exception:
|
| 56 |
+
# fallback to dict access
|
| 57 |
+
text = resp["choices"][0]["message"]["content"].strip()
|
| 58 |
+
elif openai_legacy is not None:
|
| 59 |
+
openai_legacy.api_key = api_key
|
| 60 |
+
resp = openai_legacy.ChatCompletion.create(
|
| 61 |
+
model="gpt-3.5-turbo",
|
| 62 |
+
messages=[
|
| 63 |
+
{"role": "system", "content": "You generate short Buddhist wisdom quotes."},
|
| 64 |
+
{"role": "user", "content": user_prompt},
|
| 65 |
+
],
|
| 66 |
+
max_tokens=max_tokens,
|
| 67 |
+
temperature=0.8,
|
| 68 |
+
)
|
| 69 |
+
text = resp["choices"][0]["message"]["content"].strip()
|
| 70 |
+
else:
|
| 71 |
+
logger.error("No usable OpenAI client available (install openai package)")
|
| 72 |
+
raise SystemExit(1)
|
| 73 |
+
logger.info("Received wisdom: %s", text)
|
| 74 |
+
return text
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
parser = argparse.ArgumentParser(description="Generate short Buddhism wisdom via OpenAI")
|
| 79 |
+
parser.add_argument("-p", "--prompt", help="Optional topic prompt")
|
| 80 |
+
parser.add_argument("--post", action="store_true", help="Post generated wisdom to Facebook using FB_PAGE_ACCESS_TOKEN in .env")
|
| 81 |
+
parser.add_argument("--dry-run", action="store_true", help="Print but do not post")
|
| 82 |
+
args = parser.parse_args()
|
| 83 |
+
|
| 84 |
+
wisdom = generate_wisdom(args.prompt)
|
| 85 |
+
print("Generated wisdom:\n", wisdom)
|
| 86 |
+
|
| 87 |
+
if args.post:
|
| 88 |
+
if args.dry_run:
|
| 89 |
+
logger.info("Dry run enabled — not posting to Facebook")
|
| 90 |
+
return
|
| 91 |
+
from post_to_facebook import post_to_facebook
|
| 92 |
+
from dotenv import load_dotenv
|
| 93 |
+
|
| 94 |
+
load_dotenv()
|
| 95 |
+
page_id = os.getenv("FB_PAGE_ID")
|
| 96 |
+
token = os.getenv("FB_PAGE_ACCESS_TOKEN")
|
| 97 |
+
if not page_id or not token:
|
| 98 |
+
logger.error("FB_PAGE_ID or FB_PAGE_ACCESS_TOKEN missing in environment")
|
| 99 |
+
raise SystemExit(1)
|
| 100 |
+
logger.info("Posting wisdom to Facebook page %s", page_id)
|
| 101 |
+
res = post_to_facebook(page_id, token, wisdom)
|
| 102 |
+
logger.info("Facebook response: %s", res)
|
| 103 |
+
print("Posted. Response:", res)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
hf_auth_setup.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""hf_auth_setup.py
|
| 2 |
+
|
| 3 |
+
Helper to show / set the Hugging Face spaces git remote from an HF token.
|
| 4 |
+
|
| 5 |
+
Usage: `python hf_auth_setup.py` — it will try to read token from `.env` and print the suggested remote URL.
|
| 6 |
+
If you confirm, it can add the remote for you.
|
| 7 |
+
"""
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from dotenv import load_dotenv
|
| 14 |
+
except Exception:
|
| 15 |
+
load_dotenv = None
|
| 16 |
+
|
| 17 |
+
ROOT = Path.cwd()
|
| 18 |
+
|
| 19 |
+
def load_token():
|
| 20 |
+
if load_dotenv:
|
| 21 |
+
p = ROOT / '.env'
|
| 22 |
+
if p.exists():
|
| 23 |
+
load_dotenv(p)
|
| 24 |
+
for key in ('HF_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGINGFACE_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HF'):
|
| 25 |
+
v = os.getenv(key)
|
| 26 |
+
if v:
|
| 27 |
+
return v
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
def run(cmd):
|
| 31 |
+
print('>', ' '.join(cmd))
|
| 32 |
+
return subprocess.run(cmd, cwd=ROOT)
|
| 33 |
+
|
| 34 |
+
def main():
|
| 35 |
+
token = load_token()
|
| 36 |
+
if not token:
|
| 37 |
+
print('No HF token found in .env or env. Run `huggingface-cli login` or set HF_TOKEN in .env')
|
| 38 |
+
return
|
| 39 |
+
|
| 40 |
+
repo = ROOT.name
|
| 41 |
+
username = None
|
| 42 |
+
# Try to discover username via huggingface_hub if available
|
| 43 |
+
try:
|
| 44 |
+
from huggingface_hub import HfApi
|
| 45 |
+
api = HfApi()
|
| 46 |
+
info = api.whoami(token=token)
|
| 47 |
+
username = info.get('name') or (info.get('user') or {}).get('name')
|
| 48 |
+
except Exception:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
if not username:
|
| 52 |
+
username = input('Hugging Face username (not found automatically): ').strip()
|
| 53 |
+
if not username:
|
| 54 |
+
print('Username required to compose remote. Exiting.')
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
remote = f"https://{token}@huggingface.co/spaces/{username}/{repo}.git"
|
| 58 |
+
print('\nSuggested remote URL:')
|
| 59 |
+
print(remote)
|
| 60 |
+
print('\nYou can add this remote (token will be stored in git config).')
|
| 61 |
+
ans = input('Add remote and push now? [y/N]: ').strip().lower()
|
| 62 |
+
if ans != 'y':
|
| 63 |
+
print('Done — you can add the remote manually if desired.')
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
# remove origin if exists
|
| 67 |
+
run(['git', 'remote', 'remove', 'origin'])
|
| 68 |
+
run(['git', 'remote', 'add', 'origin', remote])
|
| 69 |
+
run(['git', 'push', '-u', 'origin', 'main'])
|
| 70 |
+
print('Pushed to remote. Visit https://huggingface.co/spaces/{}/{}'.format(username, repo))
|
| 71 |
+
|
| 72 |
+
if __name__ == '__main__':
|
| 73 |
+
main()
|
post_to_facebook.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
import requests
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def post_to_facebook(page_id: str, access_token: str, message: str, link: str | None = None):
|
| 12 |
+
url = f"https://graph.facebook.com/{page_id}/feed"
|
| 13 |
+
payload = {"message": message, "access_token": access_token}
|
| 14 |
+
if link:
|
| 15 |
+
payload["link"] = link
|
| 16 |
+
logger.info("Posting to Facebook page %s", page_id)
|
| 17 |
+
resp = requests.post(url, data=payload)
|
| 18 |
+
try:
|
| 19 |
+
resp.raise_for_status()
|
| 20 |
+
except requests.HTTPError:
|
| 21 |
+
logger.error("Facebook API error: %s", resp.text)
|
| 22 |
+
raise
|
| 23 |
+
data = resp.json()
|
| 24 |
+
logger.info("Post successful: %s", data)
|
| 25 |
+
return data
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
load_dotenv()
|
| 30 |
+
parser = argparse.ArgumentParser(description="Post a message to a Facebook Page using Page Access Token from .env")
|
| 31 |
+
parser.add_argument("-m", "--message", help="Message text to post (or set MESSAGE in .env)")
|
| 32 |
+
parser.add_argument("-l", "--link", help="Optional link to include")
|
| 33 |
+
parser.add_argument("--use-app-access", action="store_true", help="Attempt to post using the app access token (APP_ID|APP_SECRET)")
|
| 34 |
+
args = parser.parse_args()
|
| 35 |
+
|
| 36 |
+
# Prefer explicit env names already present in the repo
|
| 37 |
+
page_id = os.getenv("FB_PAGE_ID") or os.getenv("PAGE_ID")
|
| 38 |
+
access_token = os.getenv("FB_PAGE_ACCESS_TOKEN") or os.getenv("PAGE_ACCESS_TOKEN")
|
| 39 |
+
message = args.message or os.getenv("MESSAGE")
|
| 40 |
+
link = args.link or os.getenv("LINK")
|
| 41 |
+
use_app_access = args.use_app_access
|
| 42 |
+
|
| 43 |
+
# build app access token if requested
|
| 44 |
+
if use_app_access:
|
| 45 |
+
app_id = os.getenv("FB_APP_ID")
|
| 46 |
+
app_secret = os.getenv("FB_APP_SECRET")
|
| 47 |
+
if not app_id or not app_secret:
|
| 48 |
+
print("ERROR: FB_APP_ID and FB_APP_SECRET required to build app access token")
|
| 49 |
+
raise SystemExit(1)
|
| 50 |
+
access_token = f"{app_id}|{app_secret}"
|
| 51 |
+
|
| 52 |
+
if not page_id or not access_token:
|
| 53 |
+
logger.error("Missing FB_PAGE_ID or FB_PAGE_ACCESS_TOKEN in environment (.env)")
|
| 54 |
+
raise SystemExit(1)
|
| 55 |
+
|
| 56 |
+
if not message:
|
| 57 |
+
logger.error("No message provided (use --message or set MESSAGE in .env)")
|
| 58 |
+
raise SystemExit(1)
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
result = post_to_facebook(page_id, access_token, message, link)
|
| 62 |
+
except requests.HTTPError as e:
|
| 63 |
+
details = e.response.text if e.response is not None else str(e)
|
| 64 |
+
logger.error("Facebook API request failed: %s", details)
|
| 65 |
+
raise SystemExit(1)
|
| 66 |
+
|
| 67 |
+
logger.info("Posted to Facebook page successfully: %s", result)
|
| 68 |
+
print("Posted to Facebook page successfully:", result)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
main()
|
push_to_space.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
HF = os.getenv('HF')
|
| 8 |
+
"""
|
| 9 |
+
ARCHIVED: push_to_space.py
|
| 10 |
+
|
| 11 |
+
Not required in the deployed Space. Kept as an archive placeholder.
|
| 12 |
+
"""
|
| 13 |
+
subprocess.run(['git','remote','add','origin', remote_with_token], check=True)
|
| 14 |
+
subprocess.run(['git','branch','-M','main'], check=False)
|
| 15 |
+
print('Pushing to remote...')
|
| 16 |
+
res = subprocess.run(['git','push','-u','origin','main'], check=False)
|
| 17 |
+
if res.returncode != 0:
|
| 18 |
+
print('git push failed with code', res.returncode)
|
| 19 |
+
sys.exit(res.returncode)
|
| 20 |
+
# replace remote with tokenless url
|
| 21 |
+
subprocess.run(['git','remote','set-url','origin', remote_no_token], check=True)
|
| 22 |
+
print('Push complete')
|
push_upload_to_space.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ARCHIVED: push_upload_to_space.py
|
| 3 |
+
|
| 4 |
+
This helper has been archived and removed from active use inside the
|
| 5 |
+
Space repository. If you need to programmatically upload, restore from
|
| 6 |
+
your development copy or use the `huggingface_hub` CLI.
|
| 7 |
+
"""
|
| 8 |
+
import os
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from huggingface_hub import upload_folder
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
HF = os.getenv('HF')
|
| 14 |
+
if not HF:
|
| 15 |
+
print('ERROR: HF token not found in .env as HF')
|
| 16 |
+
raise SystemExit(1)
|
| 17 |
+
|
| 18 |
+
repo_id = 'gowshiselva/whispermonk'
|
| 19 |
+
print('Uploading folder to', repo_id)
|
| 20 |
+
upload_folder(
|
| 21 |
+
folder_path='.',
|
| 22 |
+
path_in_repo='.',
|
| 23 |
+
repo_id=repo_id,
|
| 24 |
+
repo_type='space',
|
| 25 |
+
token=HF,
|
| 26 |
+
ignore_patterns=['.git/*','generated_images/*','*.env','*.env.bak']
|
| 27 |
+
)
|
| 28 |
+
print('Upload complete')
|
replicate_daily_job.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ARCHIVED: replicate_daily_job.py
|
| 3 |
+
|
| 4 |
+
This file was replaced with an archival placeholder. The scheduled daily job
|
| 5 |
+
is now implemented inside `app.py` for Hugging Face Space deployment.
|
| 6 |
+
|
| 7 |
+
If you need to restore or run the original standalone script, check
|
| 8 |
+
your repository history or re-create the script from backups.
|
| 9 |
+
"""
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python-dotenv>=1.0.0
|
| 2 |
+
requests>=2.0.0
|
| 3 |
+
openai>=0.27.0
|
| 4 |
+
gradio>=3.50.0
|
| 5 |
+
replicate>=0.10.0
|
| 6 |
+
huggingface-hub>=0.18.0
|
run_generate_and_post.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ARCHIVED: run_generate_and_post.py
|
| 3 |
+
|
| 4 |
+
This helper runner was replaced with an archival placeholder. The Gradio
|
| 5 |
+
app (`app.py`) now contains an optional scheduled daily job and can be used
|
| 6 |
+
to run generation+post using the configured provider order.
|
| 7 |
+
"""
|