sanch1txp commited on
Commit
db09408
·
verified ·
1 Parent(s): 5d8b872

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +83 -17
Dockerfile CHANGED
@@ -1,23 +1,89 @@
1
- # Use the official Python base image
2
- FROM python:3.10-slim
 
 
 
 
 
 
 
 
3
 
4
- # Install system dependencies (for image processing etc.)
5
- RUN apt-get update && apt-get install -y \
6
- libglib2.0-0 libsm6 libxext6 libxrender-dev && \
7
- apt-get clean && rm -rf /var/lib/apt/lists/*
8
 
9
- # Set working directory
10
- WORKDIR /code
 
 
 
11
 
12
- # Install dependencies
13
- COPY requirements.txt .
14
- RUN pip install --no-cache-dir -r requirements.txt
15
 
16
- # Copy application code
17
- COPY . .
18
 
19
- # Expose port 7860 for Hugging Face Space
20
- EXPOSE 7860
 
 
 
21
 
22
- # Hugging Face Spaces expect the app to run on port 7860
23
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ import uvicorn
4
+ import asyncio
5
+ from fastapi import FastAPI, Request
6
+ from fastapi.responses import FileResponse
7
+ from g4f.client import Client
8
+ import g4f
9
+ from uuid import uuid4
10
+ from datetime import datetime, timedelta
11
 
12
+ app = FastAPI()
 
 
 
13
 
14
+ # Securely load Hugging Face token
15
+ hf_token = os.getenv("HF_TOKEN")
16
+ if not hf_token:
17
+ raise EnvironmentError("HF_TOKEN not set. Please add it as a secret in Hugging Face Spaces.")
18
+ os.environ["HF_TOKEN"] = hf_token
19
 
20
+ # Use /tmp for write permissions on Hugging Face Spaces
21
+ IMAGE_DIR = "/tmp/generated_images"
22
+ os.makedirs(IMAGE_DIR, exist_ok=True)
23
 
24
+ # Track generated image files with timestamps
25
+ image_metadata = {}
26
 
27
+ # Silent g4f update command (every 24h)
28
+ async def auto_update_g4f():
29
+ while True:
30
+ os.system("pip install -U g4f > /dev/null 2>&1")
31
+ await asyncio.sleep(86400) # 24 hours
32
 
33
+ # Image cleanup (every minute)
34
+ async def cleanup_old_images():
35
+ while True:
36
+ now = datetime.utcnow()
37
+ for filename, meta in list(image_metadata.items()):
38
+ if now - meta['created'] > timedelta(minutes=30):
39
+ try:
40
+ os.remove(meta['path'])
41
+ del image_metadata[filename]
42
+ except Exception:
43
+ pass
44
+ await asyncio.sleep(60)
45
+
46
+ @app.get("/")
47
+ async def root():
48
+ return {"message": "🖼️ Flux Image API is running! Use /api?prompt=..."}
49
+
50
+ @app.get("/api")
51
+ async def generate_image(prompt: str):
52
+ client = Client(provider=g4f.Provider.BlackForestLabs_Flux1Dev, api_key=hf_token)
53
+ response = client.images.generate(
54
+ model="flux-dev",
55
+ prompt=prompt,
56
+ response_format="b64_json"
57
+ )
58
+
59
+ image_b64 = response.data[0].b64_json
60
+ image_bytes = base64.b64decode(image_b64)
61
+ filename = f"{uuid4().hex}.webp"
62
+ filepath = os.path.join(IMAGE_DIR, filename)
63
+
64
+ with open(filepath, "wb") as f:
65
+ f.write(image_bytes)
66
+
67
+ # Register image metadata
68
+ image_metadata[filename] = {
69
+ "created": datetime.utcnow(),
70
+ "path": filepath
71
+ }
72
+
73
+ proxy_url = f"/proxy/{filename}"
74
+ return {"url": proxy_url, "expires_in": "30 minutes"}
75
+
76
+ @app.get("/proxy/{filename}")
77
+ async def proxy_image(filename: str):
78
+ filepath = os.path.join(IMAGE_DIR, filename)
79
+ if not os.path.exists(filepath):
80
+ return {"error": "File expired or not found."}
81
+ return FileResponse(filepath, media_type="image/webp")
82
+
83
+ @app.on_event("startup")
84
+ async def startup_event():
85
+ asyncio.create_task(auto_update_g4f())
86
+ asyncio.create_task(cleanup_old_images())
87
+
88
+ # To run locally (for debugging):
89
+ # uvicorn app:app --host 0.0.0.0 --port 7860