Spaces:
Runtime error
Runtime error
setup demo app on hf
Browse filesfirst pass and getting it running
- .dockerignore +67 -0
- Dockerfile +58 -0
- README.md +40 -10
- app.py +470 -0
- deploy.md +69 -0
- events.py +27 -0
- requirements.txt +24 -0
- static/style.css +71 -0
- templates/index.html +664 -0
.dockerignore
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Python
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
*.so
|
6 |
+
.Python
|
7 |
+
build/
|
8 |
+
develop-eggs/
|
9 |
+
dist/
|
10 |
+
downloads/
|
11 |
+
eggs/
|
12 |
+
.eggs/
|
13 |
+
lib/
|
14 |
+
lib64/
|
15 |
+
parts/
|
16 |
+
sdist/
|
17 |
+
var/
|
18 |
+
wheels/
|
19 |
+
*.egg-info/
|
20 |
+
.installed.cfg
|
21 |
+
*.egg
|
22 |
+
|
23 |
+
# Virtual environments
|
24 |
+
hf/
|
25 |
+
venv/
|
26 |
+
env/
|
27 |
+
ENV/
|
28 |
+
|
29 |
+
# IDE
|
30 |
+
.vscode/
|
31 |
+
.idea/
|
32 |
+
*.swp
|
33 |
+
*.swo
|
34 |
+
|
35 |
+
# OS
|
36 |
+
.DS_Store
|
37 |
+
Thumbs.db
|
38 |
+
|
39 |
+
# Environment files
|
40 |
+
.env
|
41 |
+
.env.local
|
42 |
+
.env.example
|
43 |
+
|
44 |
+
# Logs
|
45 |
+
*.log
|
46 |
+
|
47 |
+
# Cache
|
48 |
+
.cache/
|
49 |
+
.pytest_cache/
|
50 |
+
|
51 |
+
# Model outputs
|
52 |
+
*.png
|
53 |
+
*.jpg
|
54 |
+
*.jpeg
|
55 |
+
|
56 |
+
# Git
|
57 |
+
.git/
|
58 |
+
.gitignore
|
59 |
+
|
60 |
+
# Documentation
|
61 |
+
README.md
|
62 |
+
CHANGELOG.md
|
63 |
+
LICENSE
|
64 |
+
|
65 |
+
# Scripts
|
66 |
+
create_cdp_wallet.py
|
67 |
+
generate_image.py
|
Dockerfile
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Use Python 3.11 slim image for better compatibility with HF Spaces
|
2 |
+
FROM python:3.11-slim
|
3 |
+
|
4 |
+
# Set working directory
|
5 |
+
WORKDIR /app
|
6 |
+
|
7 |
+
# Install system dependencies
|
8 |
+
RUN apt-get update && apt-get install -y \
|
9 |
+
git \
|
10 |
+
curl \
|
11 |
+
build-essential \
|
12 |
+
&& rm -rf /var/lib/apt/lists/*
|
13 |
+
|
14 |
+
# Copy requirements first for better Docker layer caching
|
15 |
+
COPY requirements.txt .
|
16 |
+
|
17 |
+
# Install Python dependencies
|
18 |
+
RUN pip install --no-cache-dir --upgrade pip
|
19 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
20 |
+
|
21 |
+
# Copy application files
|
22 |
+
COPY . .
|
23 |
+
|
24 |
+
# Create directories for models and cache
|
25 |
+
RUN mkdir -p /app/cache /app/models
|
26 |
+
|
27 |
+
# Set environment variables for HF Spaces
|
28 |
+
ENV PYTHONPATH=/app
|
29 |
+
ENV PYTHONUNBUFFERED=1
|
30 |
+
ENV HF_HOME=/app/cache
|
31 |
+
ENV TRANSFORMERS_CACHE=/app/cache
|
32 |
+
ENV TORCH_HOME=/app/cache
|
33 |
+
|
34 |
+
# Pre-download models to reduce startup time
|
35 |
+
RUN python -c "
|
36 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification
|
37 |
+
import torch
|
38 |
+
|
39 |
+
print('π¦ Pre-downloading DistilGPT-2...')
|
40 |
+
tokenizer = AutoTokenizer.from_pretrained('distilgpt2')
|
41 |
+
model = AutoModelForCausalLM.from_pretrained('distilgpt2')
|
42 |
+
|
43 |
+
print('π¦ Pre-downloading RoBERTa sentiment model...')
|
44 |
+
sentiment_model = AutoModelForSequenceClassification.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment-latest')
|
45 |
+
sentiment_tokenizer = AutoTokenizer.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment-latest')
|
46 |
+
|
47 |
+
print('β
Models downloaded successfully!')
|
48 |
+
"
|
49 |
+
|
50 |
+
# Expose port 7860 (HF Spaces default)
|
51 |
+
EXPOSE 7860
|
52 |
+
|
53 |
+
# Health check
|
54 |
+
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 \
|
55 |
+
CMD curl -f http://localhost:7860/health || exit 1
|
56 |
+
|
57 |
+
# Run the application
|
58 |
+
CMD ["python", "app.py"]
|
README.md
CHANGED
@@ -1,12 +1,42 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
---
|
11 |
|
12 |
-
|
|
|
1 |
+
# π€ x402 AI Demo - Pay-per-use AI Services
|
2 |
+
|
3 |
+
A FastAPI demonstration of micropayments for AI services using the x402 protocol.
|
4 |
+
|
5 |
+
## π Features
|
6 |
+
|
7 |
+
- **π Text Generation** - DistilGPT-2 ($0.01 per request)
|
8 |
+
- **π Sentiment Analysis** - RoBERTa ($0.005 per request)
|
9 |
+
- **πΌοΈ Image Generation** - Amazon Nova Canvas ($0.02 per request)
|
10 |
+
- **π° Automatic Revenue Splitting** - CDP Wallet integration
|
11 |
+
- **π MetaMask Integration** - Seamless crypto payments
|
12 |
+
|
13 |
+
## π§ How It Works
|
14 |
+
|
15 |
+
1. Connect your MetaMask wallet to Base Sepolia testnet
|
16 |
+
2. Click a service button to make a request
|
17 |
+
3. Sign the x402 payment with your wallet
|
18 |
+
4. AI service processes your request
|
19 |
+
5. Revenue is automatically split between stakeholders
|
20 |
+
|
21 |
+
## π‘ Demo Mode
|
22 |
+
|
23 |
+
This is running on **Base Sepolia testnet** - no real money required! Get testnet USDC from the [Base Sepolia faucet](https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet).
|
24 |
+
|
25 |
+
## ποΈ Technology Stack
|
26 |
+
|
27 |
+
- **Backend**: FastAPI with x402 payment protocol
|
28 |
+
- **Frontend**: HTML/CSS/JavaScript with MetaMask integration
|
29 |
+
- **AI Models**: Hugging Face Transformers (DistilGPT-2, RoBERTa)
|
30 |
+
- **Image Generation**: AWS Bedrock Nova Canvas
|
31 |
+
- **Payments**: Base Sepolia testnet with USDC
|
32 |
+
- **Revenue Splitting**: Coinbase Developer Platform (CDP)
|
33 |
+
|
34 |
+
## π Links
|
35 |
+
|
36 |
+
- [x402 Protocol](https://github.com/sourcegraph/fastapi-x402)
|
37 |
+
- [Base Sepolia Faucet](https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet)
|
38 |
+
- [MetaMask Download](https://metamask.io/)
|
39 |
+
|
40 |
---
|
41 |
|
42 |
+
Built with β€οΈ using FastAPI, Hugging Face, and the x402 payment protocol.
|
app.py
ADD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|
+
import asyncio
|
12 |
+
from typing import Dict, Any
|
13 |
+
from dotenv import load_dotenv
|
14 |
+
from fastapi import FastAPI, Request, HTTPException, APIRouter
|
15 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
16 |
+
from fastapi.templating import Jinja2Templates
|
17 |
+
from fastapi.staticfiles import StaticFiles
|
18 |
+
from fastapi.middleware.cors import CORSMiddleware
|
19 |
+
from pydantic import BaseModel
|
20 |
+
import torch
|
21 |
+
from transformers import pipeline
|
22 |
+
from web3 import Web3
|
23 |
+
|
24 |
+
# New imports for CDP and AWS
|
25 |
+
import boto3
|
26 |
+
from cdp.cdp_client import CdpClient
|
27 |
+
from events import push
|
28 |
+
|
29 |
+
# Load environment variables
|
30 |
+
load_dotenv()
|
31 |
+
|
32 |
+
# Environment validation
|
33 |
+
REQUIRED_VARS = [
|
34 |
+
"PAY_TO_ADDRESS", # Required by fastapi-x402 package
|
35 |
+
]
|
36 |
+
|
37 |
+
# CDP and AWS variables (only required if using those features)
|
38 |
+
CDP_VARS = ["CDP_API_KEY", "DEV_WALLET", "HF_WALLET", "AWS_WALLET"]
|
39 |
+
AWS_VARS = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION"]
|
40 |
+
|
41 |
+
# Check required variables
|
42 |
+
for var in REQUIRED_VARS:
|
43 |
+
if not os.getenv(var):
|
44 |
+
raise ValueError(f"Missing required environment variable: {var}")
|
45 |
+
|
46 |
+
# Check CDP variables (warn if missing but don't fail)
|
47 |
+
CDP_ENABLED = all(os.getenv(var) for var in CDP_VARS)
|
48 |
+
if not CDP_ENABLED:
|
49 |
+
print(f"β οΈ CDP revenue splitting disabled. Missing: {[v for v in CDP_VARS if not os.getenv(v)]}")
|
50 |
+
|
51 |
+
# Check AWS variables (warn if missing but don't fail)
|
52 |
+
AWS_ENABLED = all(os.getenv(var) for var in AWS_VARS)
|
53 |
+
if not AWS_ENABLED:
|
54 |
+
print(f"β οΈ AWS Bedrock image generation disabled. Missing: {[v for v in AWS_VARS if not os.getenv(v)]}")
|
55 |
+
|
56 |
+
# Initialize FastAPI and x402
|
57 |
+
from fastapi_x402 import init_x402, pay
|
58 |
+
|
59 |
+
app = FastAPI(title="x402 AI Demo", description="Pay-per-use AI services")
|
60 |
+
|
61 |
+
# Add CORS middleware for web frontend
|
62 |
+
app.add_middleware(
|
63 |
+
CORSMiddleware,
|
64 |
+
allow_origins=["*"],
|
65 |
+
allow_credentials=True,
|
66 |
+
allow_methods=["*"],
|
67 |
+
allow_headers=["*"],
|
68 |
+
expose_headers=["*"],
|
69 |
+
)
|
70 |
+
|
71 |
+
# Initialize x402 with testnet for demo
|
72 |
+
init_x402(app, network=os.getenv("X402_NETWORK", "base-sepolia"))
|
73 |
+
|
74 |
+
# Setup templates and static files
|
75 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
76 |
+
templates = Jinja2Templates(directory="templates")
|
77 |
+
|
78 |
+
# Load lightweight AI models
|
79 |
+
print("π€ Loading AI models...")
|
80 |
+
|
81 |
+
# Use DistilGPT-2 - much smaller than GPT-2 but still capable
|
82 |
+
text_generator = pipeline(
|
83 |
+
"text-generation",
|
84 |
+
model="distilgpt2",
|
85 |
+
device=0 if torch.cuda.is_available() else -1
|
86 |
+
)
|
87 |
+
|
88 |
+
# Use a simple sentiment analysis model as second service
|
89 |
+
sentiment_analyzer = pipeline(
|
90 |
+
"sentiment-analysis",
|
91 |
+
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
|
92 |
+
device=0 if torch.cuda.is_available() else -1
|
93 |
+
)
|
94 |
+
|
95 |
+
print("β
Models loaded successfully!")
|
96 |
+
|
97 |
+
# AWS Bedrock setup
|
98 |
+
if AWS_ENABLED:
|
99 |
+
AWS_REGION = os.getenv("AWS_REGION", "us-west-2")
|
100 |
+
bedrock = boto3.client("bedrock-runtime", region_name=AWS_REGION)
|
101 |
+
print(f"β
AWS Bedrock client initialized in {AWS_REGION}")
|
102 |
+
|
103 |
+
def nova_canvas(prompt: str, h=512, w=512):
|
104 |
+
"""Generate image using Amazon Nova Canvas."""
|
105 |
+
seed = random.randint(0, 858_993_460)
|
106 |
+
payload = {
|
107 |
+
"taskType": "TEXT_IMAGE",
|
108 |
+
"textToImageParams": {"text": prompt},
|
109 |
+
"imageGenerationConfig": {
|
110 |
+
"seed": seed,
|
111 |
+
"quality": "standard",
|
112 |
+
"height": h,
|
113 |
+
"width": w,
|
114 |
+
"numberOfImages": 1,
|
115 |
+
},
|
116 |
+
}
|
117 |
+
try:
|
118 |
+
resp = bedrock.invoke_model(
|
119 |
+
modelId="amazon.nova-canvas-v1:0",
|
120 |
+
body=json.dumps(payload),
|
121 |
+
)
|
122 |
+
img_b64 = json.loads(resp["body"].read())["images"][0]
|
123 |
+
return img_b64
|
124 |
+
except Exception as e:
|
125 |
+
push("error", service="bedrock", error=str(e))
|
126 |
+
raise HTTPException(500, f"Bedrock error: {str(e)}")
|
127 |
+
else:
|
128 |
+
def nova_canvas(prompt: str, h=512, w=512):
|
129 |
+
raise HTTPException(503, "AWS Bedrock not configured")
|
130 |
+
|
131 |
+
# CDP revenue splitting setup
|
132 |
+
if CDP_ENABLED:
|
133 |
+
split_router = APIRouter()
|
134 |
+
|
135 |
+
SPLITS = [
|
136 |
+
{"wallet": os.environ["DEV_WALLET"], "pct": 30},
|
137 |
+
{"wallet": os.environ["HF_WALLET"], "pct": 30},
|
138 |
+
{"wallet": os.environ["AWS_WALLET"], "pct": 30},
|
139 |
+
] # 10% stays in collection wallet
|
140 |
+
print(f"β
CDP revenue splitting enabled with {len(SPLITS)} recipients")
|
141 |
+
|
142 |
+
async def split_revenue(amount_usdc: float):
|
143 |
+
"""Split revenue using CDP transfers"""
|
144 |
+
try:
|
145 |
+
async with CdpClient() as cdp:
|
146 |
+
# Get our collection account
|
147 |
+
sender = await cdp.evm.get_or_create_account(name="fastx402-demo")
|
148 |
+
|
149 |
+
for split in SPLITS:
|
150 |
+
split_amount = amount_usdc * (split["pct"] / 100)
|
151 |
+
amount_wei = Web3.toWei(split_amount, "ether") # Convert to wei
|
152 |
+
|
153 |
+
# Transfer to recipient
|
154 |
+
tx_hash = await sender.transfer(
|
155 |
+
to=split["wallet"],
|
156 |
+
amount=amount_wei,
|
157 |
+
token="usdc",
|
158 |
+
network="base-sepolia"
|
159 |
+
)
|
160 |
+
|
161 |
+
push("payout",
|
162 |
+
to=split["wallet"][:8] + "...",
|
163 |
+
usdc=split_amount,
|
164 |
+
pct=split["pct"],
|
165 |
+
tx_hash=str(tx_hash)[:10])
|
166 |
+
|
167 |
+
print(f"πΈ Sent ${split_amount:.4f} USDC to {split['wallet'][:10]}...")
|
168 |
+
|
169 |
+
return True
|
170 |
+
|
171 |
+
except Exception as e:
|
172 |
+
push("payout_error", error=str(e), amount=amount_usdc)
|
173 |
+
print(f"β Revenue split error: {e}")
|
174 |
+
return False
|
175 |
+
|
176 |
+
@split_router.post("/trigger-split")
|
177 |
+
async def trigger_split(amount: float = 0.01):
|
178 |
+
"""Manual endpoint to trigger revenue splitting (for testing)"""
|
179 |
+
success = await split_revenue(amount)
|
180 |
+
return {"success": success, "amount": amount, "splits": len(SPLITS)}
|
181 |
+
|
182 |
+
# Register CDP router with app
|
183 |
+
app.include_router(split_router)
|
184 |
+
|
185 |
+
# Request models
|
186 |
+
class TextRequest(BaseModel):
|
187 |
+
prompt: str
|
188 |
+
|
189 |
+
class SentimentRequest(BaseModel):
|
190 |
+
text: str
|
191 |
+
|
192 |
+
# Routes
|
193 |
+
@app.get("/", response_class=HTMLResponse)
|
194 |
+
async def read_root(request: Request):
|
195 |
+
"""Serve the main demo page"""
|
196 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
197 |
+
|
198 |
+
@app.get("/health")
|
199 |
+
async def health_check():
|
200 |
+
"""Health check endpoint"""
|
201 |
+
return {"status": "healthy", "models_loaded": True}
|
202 |
+
|
203 |
+
@app.post("/generate-text")
|
204 |
+
@pay("$0.01") # 1 cent for text generation
|
205 |
+
async def generate_text(request: TextRequest):
|
206 |
+
"""Generate text using DistilGPT-2"""
|
207 |
+
try:
|
208 |
+
print(f"π Generating text for: '{request.prompt}'")
|
209 |
+
push("paid_inference", service="text-gen", usdc=0.01, prompt=request.prompt[:50])
|
210 |
+
|
211 |
+
result = text_generator(
|
212 |
+
request.prompt,
|
213 |
+
max_new_tokens=50,
|
214 |
+
num_return_sequences=1,
|
215 |
+
temperature=0.8,
|
216 |
+
do_sample=True,
|
217 |
+
pad_token_id=text_generator.tokenizer.eos_token_id
|
218 |
+
)[0]['generated_text']
|
219 |
+
|
220 |
+
push("inference_success", service="text-gen", length=len(result))
|
221 |
+
|
222 |
+
# Trigger revenue split for successful payment
|
223 |
+
if CDP_ENABLED:
|
224 |
+
asyncio.create_task(split_revenue(0.01))
|
225 |
+
|
226 |
+
return {"result": result, "model": "distilgpt2"}
|
227 |
+
except Exception as e:
|
228 |
+
print(f"β Text generation error: {e}")
|
229 |
+
push("inference_error", service="text-gen", error=str(e))
|
230 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|
231 |
+
|
232 |
+
@app.post("/analyze-sentiment")
|
233 |
+
@pay("$0.005") # Half cent for sentiment analysis
|
234 |
+
async def analyze_sentiment(request: SentimentRequest):
|
235 |
+
"""Analyze sentiment using RoBERTa"""
|
236 |
+
try:
|
237 |
+
print(f"π Analyzing sentiment for: '{request.text}'")
|
238 |
+
push("paid_inference", service="sentiment", usdc=0.005, text=request.text[:50])
|
239 |
+
|
240 |
+
result = sentiment_analyzer(request.text)[0]
|
241 |
+
|
242 |
+
push("inference_success", service="sentiment", sentiment=result["label"], confidence=result["score"])
|
243 |
+
|
244 |
+
# Trigger revenue split for successful payment
|
245 |
+
if CDP_ENABLED:
|
246 |
+
asyncio.create_task(split_revenue(0.005))
|
247 |
+
|
248 |
+
return {
|
249 |
+
"text": request.text,
|
250 |
+
"sentiment": result["label"],
|
251 |
+
"confidence": round(result["score"], 3),
|
252 |
+
"model": "twitter-roberta-base-sentiment"
|
253 |
+
}
|
254 |
+
except Exception as e:
|
255 |
+
print(f"β Sentiment analysis error: {e}")
|
256 |
+
push("inference_error", service="sentiment", error=str(e))
|
257 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|
258 |
+
|
259 |
+
# Add image generation request model
|
260 |
+
class ImageRequest(BaseModel):
|
261 |
+
prompt: str
|
262 |
+
|
263 |
+
@app.post("/generate-image")
|
264 |
+
@pay("$0.02") # 2 cents for image generation
|
265 |
+
async def generate_image(request: ImageRequest):
|
266 |
+
"""Generate image using Amazon Nova Canvas"""
|
267 |
+
try:
|
268 |
+
print(f"πΌοΈ Generating image for: '{request.prompt}'")
|
269 |
+
push("paid_inference", service="image-gen", usdc=0.02, prompt=request.prompt[:50])
|
270 |
+
|
271 |
+
img_b64 = nova_canvas(request.prompt)
|
272 |
+
|
273 |
+
push("inference_success", service="image-gen", size="512x512")
|
274 |
+
|
275 |
+
# Trigger revenue split for successful payment
|
276 |
+
if CDP_ENABLED:
|
277 |
+
asyncio.create_task(split_revenue(0.02))
|
278 |
+
|
279 |
+
return {
|
280 |
+
"image": img_b64,
|
281 |
+
"model": "nova-canvas-v1",
|
282 |
+
"prompt": request.prompt
|
283 |
+
}
|
284 |
+
except Exception as e:
|
285 |
+
print(f"β Image generation error: {e}")
|
286 |
+
push("inference_error", service="image-gen", error=str(e))
|
287 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|
288 |
+
|
289 |
+
@app.get("/debug")
|
290 |
+
async def debug_info():
|
291 |
+
"""Debug endpoint to check x402 configuration"""
|
292 |
+
from fastapi_x402.core import get_config, get_facilitator_client
|
293 |
+
|
294 |
+
config = get_config()
|
295 |
+
facilitator = get_facilitator_client()
|
296 |
+
|
297 |
+
return {
|
298 |
+
"network": config.network,
|
299 |
+
"facilitator_url": facilitator.base_url,
|
300 |
+
"is_coinbase_cdp": facilitator.is_coinbase_cdp,
|
301 |
+
"device": "cuda" if torch.cuda.is_available() else "cpu",
|
302 |
+
"models": ["distilgpt2", "twitter-roberta-base-sentiment"],
|
303 |
+
"features": {
|
304 |
+
"cdp_enabled": CDP_ENABLED,
|
305 |
+
"aws_enabled": AWS_ENABLED
|
306 |
+
}
|
307 |
+
}
|
308 |
+
|
309 |
+
# Live dashboard and events API
|
310 |
+
@app.get("/events")
|
311 |
+
async def get_events():
|
312 |
+
"""Get real-time events for dashboard (JSON feed for JS)"""
|
313 |
+
from events import dump
|
314 |
+
return JSONResponse(dump())
|
315 |
+
|
316 |
+
@app.get("/splits")
|
317 |
+
async def get_splits():
|
318 |
+
"""Get revenue split configuration"""
|
319 |
+
if not CDP_ENABLED:
|
320 |
+
return {"error": "CDP not enabled"}
|
321 |
+
return {
|
322 |
+
"splits": SPLITS,
|
323 |
+
"collection_account": "fastx402-demo",
|
324 |
+
"reserve_percentage": 10
|
325 |
+
}
|
326 |
+
|
327 |
+
@app.get("/dashboard", response_class=HTMLResponse)
|
328 |
+
async def dashboard(refresh_rate: int = 2000):
|
329 |
+
"""Live revenue split dashboard"""
|
330 |
+
return f"""
|
331 |
+
<!doctype html>
|
332 |
+
<html>
|
333 |
+
<head>
|
334 |
+
<meta charset='utf-8'>
|
335 |
+
<title>x402 Live Revenue Dashboard</title>
|
336 |
+
<style>
|
337 |
+
body {{ font-family: sans-serif; margin: 40px; background: #f8fafc; }}
|
338 |
+
.container {{ max-width: 1200px; margin: 0 auto; }}
|
339 |
+
.header {{ background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
|
340 |
+
.stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px; }}
|
341 |
+
.stat-card {{ background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
|
342 |
+
.stat-value {{ font-size: 2em; font-weight: bold; color: #059669; }}
|
343 |
+
.stat-label {{ color: #6b7280; font-size: 0.9em; }}
|
344 |
+
table {{ width: 100%; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
|
345 |
+
th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #e5e7eb; }}
|
346 |
+
th {{ background: #f9fafb; font-weight: 600; }}
|
347 |
+
.event-paid {{ background: #ecfdf5; }}
|
348 |
+
.event-deposit {{ background: #fef3c7; }}
|
349 |
+
.event-payout {{ background: #e0f2fe; }}
|
350 |
+
.event-error {{ background: #fef2f2; }}
|
351 |
+
.refresh-info {{ color: #6b7280; font-size: 0.8em; margin-top: 10px; }}
|
352 |
+
</style>
|
353 |
+
</head>
|
354 |
+
<body>
|
355 |
+
<div class="container">
|
356 |
+
<div class="header">
|
357 |
+
<h1>π x402 Live Revenue Dashboard</h1>
|
358 |
+
<p>Real-time payment and revenue splitting activity</p>
|
359 |
+
<div class="refresh-info">Auto-refreshes every {refresh_rate/1000}s</div>
|
360 |
+
</div>
|
361 |
+
|
362 |
+
<div class="stats" id="stats">
|
363 |
+
<div class="stat-card">
|
364 |
+
<div class="stat-value" id="total-payments">0</div>
|
365 |
+
<div class="stat-label">Total Payments</div>
|
366 |
+
</div>
|
367 |
+
<div class="stat-card">
|
368 |
+
<div class="stat-value" id="total-revenue">$0.00</div>
|
369 |
+
<div class="stat-label">Total Revenue</div>
|
370 |
+
</div>
|
371 |
+
<div class="stat-card">
|
372 |
+
<div class="stat-value" id="total-payouts">0</div>
|
373 |
+
<div class="stat-label">Payouts Made</div>
|
374 |
+
</div>
|
375 |
+
</div>
|
376 |
+
|
377 |
+
<table>
|
378 |
+
<thead>
|
379 |
+
<tr>
|
380 |
+
<th>Time</th>
|
381 |
+
<th>Event</th>
|
382 |
+
<th>Details</th>
|
383 |
+
</tr>
|
384 |
+
</thead>
|
385 |
+
<tbody id="events-log"></tbody>
|
386 |
+
</table>
|
387 |
+
</div>
|
388 |
+
|
389 |
+
<script>
|
390 |
+
let totalPayments = 0;
|
391 |
+
let totalRevenue = 0;
|
392 |
+
let totalPayouts = 0;
|
393 |
+
|
394 |
+
async function updateDashboard() {{
|
395 |
+
try {{
|
396 |
+
const response = await fetch('/events');
|
397 |
+
const events = await response.json();
|
398 |
+
|
399 |
+
// Reset counters
|
400 |
+
totalPayments = 0;
|
401 |
+
totalRevenue = 0;
|
402 |
+
totalPayouts = 0;
|
403 |
+
|
404 |
+
// Update event log
|
405 |
+
const tbody = document.getElementById('events-log');
|
406 |
+
tbody.innerHTML = '';
|
407 |
+
|
408 |
+
events.forEach(event => {{
|
409 |
+
const row = document.createElement('tr');
|
410 |
+
let className = '';
|
411 |
+
let details = '';
|
412 |
+
|
413 |
+
// Calculate stats and format details
|
414 |
+
switch(event.kind) {{
|
415 |
+
case 'paid_inference':
|
416 |
+
totalPayments++;
|
417 |
+
totalRevenue += event.usdc || 0;
|
418 |
+
className = 'event-paid';
|
419 |
+
details = `Service: ${{event.service}}, Amount: $${{(event.usdc || 0).toFixed(3)}}`;
|
420 |
+
break;
|
421 |
+
case 'deposit':
|
422 |
+
className = 'event-deposit';
|
423 |
+
details = `TX: ${{event.tx}}, Amount: $${{(event.usdc || 0).toFixed(3)}}`;
|
424 |
+
break;
|
425 |
+
case 'payout':
|
426 |
+
totalPayouts++;
|
427 |
+
className = 'event-payout';
|
428 |
+
details = `To: ${{event.to}}, Amount: $${{(event.usdc || 0).toFixed(3)}} (${{event.pct}}%)`;
|
429 |
+
break;
|
430 |
+
case 'inference_error':
|
431 |
+
case 'error':
|
432 |
+
case 'webhook_error':
|
433 |
+
className = 'event-error';
|
434 |
+
details = `Error: ${{event.error}}`;
|
435 |
+
break;
|
436 |
+
default:
|
437 |
+
details = JSON.stringify(event);
|
438 |
+
}}
|
439 |
+
|
440 |
+
row.className = className;
|
441 |
+
row.innerHTML = `
|
442 |
+
<td>${{event.t}}</td>
|
443 |
+
<td>${{event.kind}}</td>
|
444 |
+
<td>${{details}}</td>
|
445 |
+
`;
|
446 |
+
tbody.appendChild(row);
|
447 |
+
}});
|
448 |
+
|
449 |
+
// Update stats
|
450 |
+
document.getElementById('total-payments').textContent = totalPayments;
|
451 |
+
document.getElementById('total-revenue').textContent = `$${{totalRevenue.toFixed(3)}}`;
|
452 |
+
document.getElementById('total-payouts').textContent = totalPayouts;
|
453 |
+
|
454 |
+
}} catch (error) {{
|
455 |
+
console.error('Dashboard update failed:', error);
|
456 |
+
}}
|
457 |
+
}}
|
458 |
+
|
459 |
+
// Initial load and periodic updates
|
460 |
+
updateDashboard();
|
461 |
+
setInterval(updateDashboard, {refresh_rate});
|
462 |
+
</script>
|
463 |
+
</body>
|
464 |
+
</html>
|
465 |
+
"""
|
466 |
+
|
467 |
+
if __name__ == "__main__":
|
468 |
+
import uvicorn
|
469 |
+
# Disable uvloop to avoid async context issues, use standard asyncio instead
|
470 |
+
uvicorn.run(app, host="0.0.0.0", port=7860, loop="asyncio")
|
deploy.md
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# π Deploying to Hugging Face Spaces
|
2 |
+
|
3 |
+
## Quick Setup
|
4 |
+
|
5 |
+
1. **Create a new Space**:
|
6 |
+
- Go to https://huggingface.co/new-space
|
7 |
+
- Choose "Docker" as SDK
|
8 |
+
- Set visibility to "Public"
|
9 |
+
|
10 |
+
2. **Upload Files**:
|
11 |
+
Upload these files to your Space repository:
|
12 |
+
```
|
13 |
+
app.py
|
14 |
+
events.py
|
15 |
+
requirements.txt
|
16 |
+
Dockerfile
|
17 |
+
.dockerignore
|
18 |
+
templates/
|
19 |
+
static/
|
20 |
+
```
|
21 |
+
|
22 |
+
3. **Set Environment Variables**:
|
23 |
+
In your Space settings, add these secrets:
|
24 |
+
|
25 |
+
**Required:**
|
26 |
+
- `PAY_TO_ADDRESS`: Your wallet address for receiving payments
|
27 |
+
- `X402_NETWORK`: `base-sepolia`
|
28 |
+
|
29 |
+
**Optional (for revenue splitting):**
|
30 |
+
- `CDP_API_KEY_ID`: Your CDP API key ID
|
31 |
+
- `CDP_API_KEY_SECRET`: Your CDP API key secret
|
32 |
+
- `CDP_WALLET_SECRET`: Your CDP wallet secret
|
33 |
+
- `DEV_WALLET`: Developer wallet address
|
34 |
+
- `HF_WALLET`: Hugging Face wallet address
|
35 |
+
- `AWS_WALLET`: AWS wallet address
|
36 |
+
|
37 |
+
**Optional (for image generation):**
|
38 |
+
- `AWS_ACCESS_KEY_ID`: Your AWS access key
|
39 |
+
- `AWS_SECRET_ACCESS_KEY`: Your AWS secret key
|
40 |
+
- `AWS_REGION`: `us-east-1`
|
41 |
+
|
42 |
+
4. **Build and Deploy**:
|
43 |
+
- Push files to your Space repository
|
44 |
+
- HF Spaces will automatically build using the Dockerfile
|
45 |
+
- First build takes ~5-10 minutes (downloading models)
|
46 |
+
- Subsequent builds are faster due to Docker layer caching
|
47 |
+
|
48 |
+
## Testing
|
49 |
+
|
50 |
+
1. Visit your Space URL
|
51 |
+
2. Connect MetaMask to Base Sepolia
|
52 |
+
3. Get testnet USDC from [Base Sepolia faucet](https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet)
|
53 |
+
4. Test the three services:
|
54 |
+
- Text Generation ($0.01)
|
55 |
+
- Sentiment Analysis ($0.005)
|
56 |
+
- Image Generation ($0.02)
|
57 |
+
|
58 |
+
## Troubleshooting
|
59 |
+
|
60 |
+
- **Build fails**: Check logs for missing dependencies
|
61 |
+
- **Models loading slowly**: First startup takes time to download models
|
62 |
+
- **Payment fails**: Ensure MetaMask is on Base Sepolia with testnet USDC
|
63 |
+
- **Image generation fails**: Check AWS credentials and Bedrock model access
|
64 |
+
|
65 |
+
## Performance Notes
|
66 |
+
|
67 |
+
- **Memory**: ~4GB for all models
|
68 |
+
- **Startup**: ~30-60 seconds after build
|
69 |
+
- **Cold start**: ~10-20 seconds on first request
|
events.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# events.py - In-memory event logging for real-time dashboard
|
2 |
+
import collections
|
3 |
+
import threading
|
4 |
+
import time
|
5 |
+
from typing import Dict, List, Any
|
6 |
+
|
7 |
+
_LOG = collections.deque(maxlen=50)
|
8 |
+
_LOCK = threading.Lock()
|
9 |
+
|
10 |
+
def push(kind: str, **kv) -> None:
|
11 |
+
"""Add an event to the log with timestamp."""
|
12 |
+
with _LOCK:
|
13 |
+
_LOG.appendleft({
|
14 |
+
"t": time.strftime("%H:%M:%S"),
|
15 |
+
"kind": kind,
|
16 |
+
**kv
|
17 |
+
})
|
18 |
+
|
19 |
+
def dump() -> List[Dict[str, Any]]:
|
20 |
+
"""Get all logged events (most recent first)."""
|
21 |
+
with _LOCK:
|
22 |
+
return list(_LOG)
|
23 |
+
|
24 |
+
def clear() -> None:
|
25 |
+
"""Clear all logged events."""
|
26 |
+
with _LOCK:
|
27 |
+
_LOG.clear()
|
requirements.txt
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# FastAPI and x402
|
2 |
+
fastapi>=0.104.0
|
3 |
+
uvicorn[standard]>=0.24.0
|
4 |
+
python-dotenv>=1.0.0
|
5 |
+
fastapi-x402>=0.1.6
|
6 |
+
|
7 |
+
# AI/ML libraries
|
8 |
+
torch>=2.0.0
|
9 |
+
transformers>=4.35.0
|
10 |
+
accelerate>=0.24.0
|
11 |
+
|
12 |
+
# Web framework dependencies
|
13 |
+
jinja2>=3.1.0
|
14 |
+
python-multipart>=0.0.6
|
15 |
+
pydantic>=2.0.0
|
16 |
+
aiofiles>=23.0.0
|
17 |
+
|
18 |
+
# Optional: for better performance
|
19 |
+
# tokenizers>=0.15.0
|
20 |
+
|
21 |
+
# New additions for CDP and AWS Bedrock
|
22 |
+
boto3>=1.34.0
|
23 |
+
cdp-sdk>=0.21.0
|
24 |
+
web3>=6.0.0
|
static/style.css
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* Custom styles for x402 AI Demo */
|
2 |
+
|
3 |
+
.btn {
|
4 |
+
@apply px-4 py-2 rounded-lg font-medium transition-colors duration-200;
|
5 |
+
}
|
6 |
+
|
7 |
+
.btn-primary {
|
8 |
+
@apply bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed;
|
9 |
+
}
|
10 |
+
|
11 |
+
.price-tag {
|
12 |
+
@apply inline-block bg-green-100 text-green-800 text-sm font-semibold px-3 py-1 rounded-full mb-3;
|
13 |
+
}
|
14 |
+
|
15 |
+
.service-card {
|
16 |
+
@apply border-t-4 border-blue-500;
|
17 |
+
}
|
18 |
+
|
19 |
+
.result-box {
|
20 |
+
@apply min-h-16 p-4 bg-gray-50 rounded-lg border;
|
21 |
+
}
|
22 |
+
|
23 |
+
.loading {
|
24 |
+
@apply text-center text-gray-600 animate-pulse;
|
25 |
+
}
|
26 |
+
|
27 |
+
.success-result {
|
28 |
+
@apply p-4 bg-green-50 border border-green-200 rounded-lg;
|
29 |
+
}
|
30 |
+
|
31 |
+
.error-result {
|
32 |
+
@apply p-4 bg-red-50 border border-red-200 rounded-lg;
|
33 |
+
}
|
34 |
+
|
35 |
+
.payment-required {
|
36 |
+
@apply p-4 bg-orange-50 border border-orange-200 rounded-lg;
|
37 |
+
}
|
38 |
+
|
39 |
+
.sentiment-result {
|
40 |
+
@apply text-center py-2;
|
41 |
+
}
|
42 |
+
|
43 |
+
/* Loading animation */
|
44 |
+
@keyframes pulse {
|
45 |
+
0%, 100% { opacity: 1; }
|
46 |
+
50% { opacity: 0.5; }
|
47 |
+
}
|
48 |
+
|
49 |
+
.animate-pulse {
|
50 |
+
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
51 |
+
}
|
52 |
+
|
53 |
+
/* Code blocks */
|
54 |
+
code {
|
55 |
+
@apply bg-gray-100 px-1 py-0.5 rounded text-sm font-mono;
|
56 |
+
}
|
57 |
+
|
58 |
+
pre {
|
59 |
+
@apply text-xs font-mono whitespace-pre-wrap;
|
60 |
+
}
|
61 |
+
|
62 |
+
/* Responsive design */
|
63 |
+
@media (max-width: 768px) {
|
64 |
+
.container {
|
65 |
+
@apply px-2;
|
66 |
+
}
|
67 |
+
|
68 |
+
.service-card {
|
69 |
+
@apply p-4;
|
70 |
+
}
|
71 |
+
}
|
templates/index.html
ADDED
@@ -0,0 +1,664 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!DOCTYPE html>
|
2 |
+
<html lang="en">
|
3 |
+
<head>
|
4 |
+
<meta charset="UTF-8">
|
5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
6 |
+
<title>x402 AI Demo - Pay-per-use AI Services</title>
|
7 |
+
<link rel="stylesheet" href="/static/style.css">
|
8 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
9 |
+
</head>
|
10 |
+
<body class="bg-gray-50 min-h-screen">
|
11 |
+
<div class="container mx-auto px-4 py-8 max-w-4xl">
|
12 |
+
<header class="text-center mb-12">
|
13 |
+
<h1 class="text-4xl font-bold text-gray-900 mb-4">π€ x402 AI Demo π€</h1>
|
14 |
+
<p class="text-xl text-gray-600">Pay-per-use AI services powered by FastAPI and fastapi-x402</p>
|
15 |
+
<div class="mt-4 p-4 bg-blue-50 rounded-lg">
|
16 |
+
<p class="text-sm text-blue-800">
|
17 |
+
<strong>Demo Mode:</strong> Using testnet (Base Sepolia) - No real money required!
|
18 |
+
</p>
|
19 |
+
</div>
|
20 |
+
|
21 |
+
<!-- Wallet Connection -->
|
22 |
+
<div class="mt-6">
|
23 |
+
<button id="connect-wallet" class="btn btn-primary">
|
24 |
+
π¦ Connect MetaMask
|
25 |
+
</button>
|
26 |
+
<div id="wallet-status" class="mt-2 text-sm"></div>
|
27 |
+
</div>
|
28 |
+
</header>
|
29 |
+
|
30 |
+
<!-- Service Cards -->
|
31 |
+
<div class="grid md:grid-cols-3 gap-6">
|
32 |
+
<!-- Text Generation Service -->
|
33 |
+
<div class="service-card bg-white rounded-lg shadow-md p-6">
|
34 |
+
<h2 class="text-2xl font-semibold mb-2">π Text Generation</h2>
|
35 |
+
<div class="price-tag">$0.01 per request</div>
|
36 |
+
<p class="text-gray-600 mb-4">Generate creative text using DistilGPT-2</p>
|
37 |
+
|
38 |
+
<div class="form-group">
|
39 |
+
<label class="block text-sm font-medium mb-2">Prompt:</label>
|
40 |
+
<input
|
41 |
+
type="text"
|
42 |
+
id="text-prompt"
|
43 |
+
placeholder="Once upon a time..."
|
44 |
+
class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
|
45 |
+
value="The future of AI is"
|
46 |
+
>
|
47 |
+
<button
|
48 |
+
id="text-btn"
|
49 |
+
class="btn btn-primary mt-3 w-full"
|
50 |
+
>
|
51 |
+
Generate Text
|
52 |
+
</button>
|
53 |
+
</div>
|
54 |
+
<div id="text-result" class="result-box mt-4"></div>
|
55 |
+
</div>
|
56 |
+
|
57 |
+
<!-- Sentiment Analysis Service -->
|
58 |
+
<div class="service-card bg-white rounded-lg shadow-md p-6">
|
59 |
+
<h2 class="text-2xl font-semibold mb-2"> Sentiment Analysis</h2>
|
60 |
+
<div class="price-tag">$0.005 per request</div>
|
61 |
+
<p class="text-gray-600 mb-4">Analyze text sentiment using RoBERTa</p>
|
62 |
+
|
63 |
+
<div class="form-group">
|
64 |
+
<label class="block text-sm font-medium mb-2">Text to analyze:</label>
|
65 |
+
<textarea
|
66 |
+
id="sentiment-text"
|
67 |
+
placeholder="I love this new technology!"
|
68 |
+
class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
|
69 |
+
rows="3"
|
70 |
+
>I love using AI for creative projects!</textarea>
|
71 |
+
<button
|
72 |
+
id="sentiment-btn"
|
73 |
+
class="btn btn-primary mt-3 w-full"
|
74 |
+
>
|
75 |
+
Analyze Sentiment
|
76 |
+
</button>
|
77 |
+
</div>
|
78 |
+
<div id="sentiment-result" class="result-box mt-4"></div>
|
79 |
+
</div>
|
80 |
+
|
81 |
+
<!-- Image Generation Service -->
|
82 |
+
<div class="service-card bg-white rounded-lg shadow-md p-6">
|
83 |
+
<h2 class="text-2xl font-semibold mb-2">πΌοΈ Image Generation</h2>
|
84 |
+
<div class="price-tag">$0.02 per request</div>
|
85 |
+
<p class="text-gray-600 mb-4">Generate images using Amazon Nova Canvas</p>
|
86 |
+
|
87 |
+
<div class="form-group">
|
88 |
+
<label class="block text-sm font-medium mb-2">Prompt:</label>
|
89 |
+
<input
|
90 |
+
type="text"
|
91 |
+
id="image-prompt"
|
92 |
+
placeholder="A futuristic city skyline at sunset..."
|
93 |
+
class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
|
94 |
+
value="A beautiful mountain landscape with a lake"
|
95 |
+
>
|
96 |
+
<button
|
97 |
+
id="image-btn"
|
98 |
+
class="btn btn-primary mt-3 w-full"
|
99 |
+
>
|
100 |
+
Generate Image
|
101 |
+
</button>
|
102 |
+
</div>
|
103 |
+
<div id="image-result" class="result-box mt-4"></div>
|
104 |
+
</div>
|
105 |
+
</div>
|
106 |
+
|
107 |
+
<!-- How it Works -->
|
108 |
+
<div class="mt-12 bg-white rounded-lg shadow-md p-6">
|
109 |
+
<h3 class="text-xl font-semibold mb-4">π§ How it Works</h3>
|
110 |
+
<ol class="list-decimal list-inside space-y-2 text-gray-700">
|
111 |
+
<li>Click a service button to make a request</li>
|
112 |
+
<li>FastAPI returns <code class="bg-gray-100 px-1 rounded">402 Payment Required</code> with payment details</li>
|
113 |
+
<li>Your x402-compatible client (like MetaMask) signs the payment</li>
|
114 |
+
<li>FastAPI verifies the payment with the facilitator</li>
|
115 |
+
<li>AI service processes your request and returns results</li>
|
116 |
+
</ol>
|
117 |
+
<div class="mt-4 p-3 bg-yellow-50 rounded-lg">
|
118 |
+
<p class="text-sm text-yellow-800">
|
119 |
+
<strong>Note:</strong> This demo requires an x402-compatible client.
|
120 |
+
Try the <a href="/debug" class="text-blue-600 underline">debug endpoint</a> to check configuration.
|
121 |
+
</p>
|
122 |
+
</div>
|
123 |
+
</div>
|
124 |
+
</div>
|
125 |
+
|
126 |
+
<script type="module">
|
127 |
+
import * as viem from 'https://esm.sh/[email protected]';
|
128 |
+
|
129 |
+
// Global wallet state
|
130 |
+
let walletClient = null;
|
131 |
+
let currentAccount = null;
|
132 |
+
|
133 |
+
// Initialize wallet connection on page load
|
134 |
+
document.addEventListener('DOMContentLoaded', initWallet);
|
135 |
+
|
136 |
+
async function initWallet() {
|
137 |
+
const connectBtn = document.getElementById('connect-wallet');
|
138 |
+
const statusDiv = document.getElementById('wallet-status');
|
139 |
+
|
140 |
+
if (typeof window.ethereum === 'undefined') {
|
141 |
+
statusDiv.innerHTML = '<span class="text-red-600">β MetaMask not installed</span>';
|
142 |
+
connectBtn.disabled = true;
|
143 |
+
connectBtn.textContent = 'Install MetaMask';
|
144 |
+
connectBtn.onclick = () => window.open('https://metamask.io/', '_blank');
|
145 |
+
return;
|
146 |
+
}
|
147 |
+
|
148 |
+
// Check if already connected
|
149 |
+
try {
|
150 |
+
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
|
151 |
+
if (accounts.length > 0) {
|
152 |
+
await connectWallet();
|
153 |
+
}
|
154 |
+
} catch (error) {
|
155 |
+
console.log('No existing connection');
|
156 |
+
}
|
157 |
+
|
158 |
+
connectBtn.onclick = connectWallet;
|
159 |
+
}
|
160 |
+
|
161 |
+
async function connectWallet() {
|
162 |
+
const connectBtn = document.getElementById('connect-wallet');
|
163 |
+
const statusDiv = document.getElementById('wallet-status');
|
164 |
+
|
165 |
+
try {
|
166 |
+
// Request account access
|
167 |
+
await window.ethereum.request({ method: 'eth_requestAccounts' });
|
168 |
+
|
169 |
+
// Switch to Base Sepolia if not already on it
|
170 |
+
try {
|
171 |
+
await window.ethereum.request({
|
172 |
+
method: 'wallet_switchEthereumChain',
|
173 |
+
params: [{ chainId: '0x14a34' }], // Base Sepolia chainId in hex
|
174 |
+
});
|
175 |
+
} catch (switchError) {
|
176 |
+
// Chain not added, try to add it
|
177 |
+
if (switchError.code === 4902) {
|
178 |
+
await window.ethereum.request({
|
179 |
+
method: 'wallet_addEthereumChain',
|
180 |
+
params: [{
|
181 |
+
chainId: '0x14a34',
|
182 |
+
chainName: 'Base Sepolia',
|
183 |
+
nativeCurrency: {
|
184 |
+
name: 'ETH',
|
185 |
+
symbol: 'ETH',
|
186 |
+
decimals: 18,
|
187 |
+
},
|
188 |
+
rpcUrls: ['https://sepolia.base.org'],
|
189 |
+
blockExplorerUrls: ['https://sepolia-explorer.base.org'],
|
190 |
+
}],
|
191 |
+
});
|
192 |
+
} else {
|
193 |
+
throw switchError;
|
194 |
+
}
|
195 |
+
}
|
196 |
+
|
197 |
+
// Create wallet client with viem
|
198 |
+
walletClient = viem.createWalletClient({
|
199 |
+
transport: viem.custom(window.ethereum),
|
200 |
+
chain: viem.baseSepolia, // Base Sepolia testnet
|
201 |
+
});
|
202 |
+
|
203 |
+
// Get account
|
204 |
+
const [address] = await walletClient.getAddresses();
|
205 |
+
currentAccount = address;
|
206 |
+
|
207 |
+
// Update UI
|
208 |
+
connectBtn.textContent = `β
${currentAccount.slice(0, 6)}...${currentAccount.slice(-4)}`;
|
209 |
+
connectBtn.disabled = true;
|
210 |
+
statusDiv.innerHTML = '<span class="text-green-600">π Wallet connected to Base Sepolia! Ready to make payments.</span>';
|
211 |
+
|
212 |
+
console.log('β
Wallet connected:', currentAccount);
|
213 |
+
|
214 |
+
} catch (error) {
|
215 |
+
console.error('β Failed to connect wallet:', error);
|
216 |
+
let errorMessage = 'Connection failed';
|
217 |
+
if (error.code === 4001) {
|
218 |
+
errorMessage = 'User rejected connection';
|
219 |
+
} else if (error.code === -32002) {
|
220 |
+
errorMessage = 'Connection request pending';
|
221 |
+
}
|
222 |
+
statusDiv.innerHTML = `<span class="text-red-600">β ${errorMessage}</span>`;
|
223 |
+
}
|
224 |
+
}
|
225 |
+
|
226 |
+
// Create x402 payment signature using TransferWithAuthorization EIP-712 (matches facilitator exactly)
|
227 |
+
async function createPaymentSignature(paymentRequirements) {
|
228 |
+
if (!walletClient || !currentAccount) {
|
229 |
+
throw new Error('Wallet not connected');
|
230 |
+
}
|
231 |
+
|
232 |
+
console.log('π§ Creating payment signature...');
|
233 |
+
|
234 |
+
// Wait a bit to ensure wallet is fully ready (helps with race conditions)
|
235 |
+
await new Promise(resolve => setTimeout(resolve, 100));
|
236 |
+
|
237 |
+
// Double-check wallet state
|
238 |
+
try {
|
239 |
+
const accounts = await walletClient.getAddresses();
|
240 |
+
if (!accounts || accounts.length === 0) {
|
241 |
+
throw new Error('No accounts available');
|
242 |
+
}
|
243 |
+
currentAccount = accounts[0]; // Refresh current account
|
244 |
+
console.log('π Wallet verification - current account:', currentAccount);
|
245 |
+
} catch (error) {
|
246 |
+
console.error('β Wallet verification failed:', error);
|
247 |
+
throw new Error('Wallet not ready for signing');
|
248 |
+
}
|
249 |
+
|
250 |
+
// Generate nonce and deadline - ensuring proper format to avoid BigInt issues
|
251 |
+
const currentTime = Math.floor(Date.now() / 1000);
|
252 |
+
const validAfter = currentTime - 60; // Valid 1 minute ago (account for clock skew)
|
253 |
+
const validBefore = currentTime + paymentRequirements.maxTimeoutSeconds; // Valid until timeout
|
254 |
+
|
255 |
+
// Create a proper 32-byte nonce (64 hex chars) that won't cause BigInt issues
|
256 |
+
const randomBytes = new Uint8Array(32);
|
257 |
+
crypto.getRandomValues(randomBytes);
|
258 |
+
const nonce = '0x' + Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
259 |
+
|
260 |
+
console.log('π Generated nonce:', nonce, 'length:', nonce.length);
|
261 |
+
|
262 |
+
// EIP-712 domain for TransferWithAuthorization (matches facilitator exactly)
|
263 |
+
const domain = {
|
264 |
+
name: paymentRequirements.extra?.name || 'USDC',
|
265 |
+
version: paymentRequirements.extra?.version || '2',
|
266 |
+
chainId: 84532, // Base Sepolia
|
267 |
+
verifyingContract: paymentRequirements.asset,
|
268 |
+
};
|
269 |
+
|
270 |
+
// EIP-712 types for TransferWithAuthorization (matches facilitator)
|
271 |
+
const types = {
|
272 |
+
TransferWithAuthorization: [
|
273 |
+
{ name: 'from', type: 'address' },
|
274 |
+
{ name: 'to', type: 'address' },
|
275 |
+
{ name: 'value', type: 'uint256' },
|
276 |
+
{ name: 'validAfter', type: 'uint256' },
|
277 |
+
{ name: 'validBefore', type: 'uint256' },
|
278 |
+
{ name: 'nonce', type: 'bytes32' },
|
279 |
+
],
|
280 |
+
};
|
281 |
+
|
282 |
+
// Create the authorization message (ensure all values are strings, no BigInt)
|
283 |
+
const message = {
|
284 |
+
from: String(currentAccount),
|
285 |
+
to: String(paymentRequirements.payTo),
|
286 |
+
value: String(paymentRequirements.maxAmountRequired), // Ensure string
|
287 |
+
validAfter: String(validAfter),
|
288 |
+
validBefore: String(validBefore),
|
289 |
+
nonce: String(nonce),
|
290 |
+
};
|
291 |
+
|
292 |
+
console.log('π Signing TransferWithAuthorization message:', message);
|
293 |
+
console.log('π Domain:', domain);
|
294 |
+
console.log('π Message types:', typeof message.value, typeof message.validAfter, typeof message.validBefore);
|
295 |
+
|
296 |
+
// Sign the EIP-712 TransferWithAuthorization message
|
297 |
+
const signature = await walletClient.signTypedData({
|
298 |
+
account: currentAccount,
|
299 |
+
domain,
|
300 |
+
types,
|
301 |
+
primaryType: 'TransferWithAuthorization',
|
302 |
+
message,
|
303 |
+
});
|
304 |
+
|
305 |
+
// Create payment payload (ensure all values are strings to avoid BigInt issues)
|
306 |
+
const paymentPayload = {
|
307 |
+
x402Version: 1,
|
308 |
+
scheme: 'exact',
|
309 |
+
network: 'base-sepolia',
|
310 |
+
payload: {
|
311 |
+
signature: String(signature),
|
312 |
+
authorization: {
|
313 |
+
from: String(currentAccount),
|
314 |
+
to: String(paymentRequirements.payTo),
|
315 |
+
value: String(paymentRequirements.maxAmountRequired),
|
316 |
+
validAfter: String(validAfter),
|
317 |
+
validBefore: String(validBefore),
|
318 |
+
nonce: String(nonce),
|
319 |
+
},
|
320 |
+
},
|
321 |
+
};
|
322 |
+
|
323 |
+
console.log('π PaymentPayload before JSON.stringify:', paymentPayload);
|
324 |
+
console.log('π Authorization value type:', typeof paymentPayload.payload.authorization.value);
|
325 |
+
|
326 |
+
// Encode as base64 for X-Payment header (handle any BigInt values)
|
327 |
+
let paymentJson;
|
328 |
+
try {
|
329 |
+
paymentJson = JSON.stringify(paymentPayload, (key, value) => {
|
330 |
+
// Log any BigInt values we encounter
|
331 |
+
if (typeof value === 'bigint') {
|
332 |
+
console.warn('β οΈ Found BigInt in paymentPayload:', key, value);
|
333 |
+
return value.toString();
|
334 |
+
}
|
335 |
+
return value;
|
336 |
+
});
|
337 |
+
} catch (error) {
|
338 |
+
console.error('β JSON.stringify error:', error);
|
339 |
+
console.error('β PaymentPayload causing error:', paymentPayload);
|
340 |
+
throw new Error(`Failed to serialize payment: ${error.message}`);
|
341 |
+
}
|
342 |
+
const paymentHeader = btoa(paymentJson);
|
343 |
+
|
344 |
+
console.log('β
TransferWithAuthorization signature created');
|
345 |
+
|
346 |
+
// Debug: decode and check the payment header for any issues
|
347 |
+
try {
|
348 |
+
const decodedPayload = JSON.parse(atob(paymentHeader));
|
349 |
+
console.log('π Decoded payment payload:', decodedPayload);
|
350 |
+
|
351 |
+
// Check timing - this might be the issue
|
352 |
+
const now = Math.floor(Date.now() / 1000);
|
353 |
+
const validAfter = Number(decodedPayload.payload.authorization.validAfter);
|
354 |
+
const validBefore = Number(decodedPayload.payload.authorization.validBefore);
|
355 |
+
|
356 |
+
console.log('π Current time:', now);
|
357 |
+
console.log('π ValidAfter:', validAfter, '(diff:', now - validAfter, 'seconds)');
|
358 |
+
console.log('π ValidBefore:', validBefore, '(diff:', validBefore - now, 'seconds)');
|
359 |
+
|
360 |
+
// Check timing issues
|
361 |
+
if (now < validAfter) {
|
362 |
+
console.warn('β οΈ Payment not valid yet! Current time is before validAfter');
|
363 |
+
}
|
364 |
+
if (now >= validBefore) {
|
365 |
+
console.warn('β οΈ Payment expired! Current time is after validBefore');
|
366 |
+
}
|
367 |
+
|
368 |
+
// Check authorization structure
|
369 |
+
const auth = decodedPayload.payload.authorization;
|
370 |
+
console.log('π Authorization:', {
|
371 |
+
from: auth.from,
|
372 |
+
to: auth.to,
|
373 |
+
value: auth.value,
|
374 |
+
nonce: auth.nonce
|
375 |
+
});
|
376 |
+
|
377 |
+
} catch (error) {
|
378 |
+
console.error('β Failed to decode payment header:', error);
|
379 |
+
}
|
380 |
+
|
381 |
+
return paymentHeader;
|
382 |
+
}
|
383 |
+
|
384 |
+
// Display API results
|
385 |
+
function displayResult(endpoint, result, resultDiv) {
|
386 |
+
if (endpoint.includes('text')) {
|
387 |
+
resultDiv.innerHTML = `
|
388 |
+
<div class="success-result">
|
389 |
+
<h4 class="font-semibold text-green-600 mb-2">Generated Text</h4>
|
390 |
+
<p class="text-gray-800 italic">"${result.result}"</p>
|
391 |
+
<small class="text-gray-500">Model: ${result.model}</small>
|
392 |
+
</div>
|
393 |
+
`;
|
394 |
+
} else if (endpoint.includes('sentiment')) {
|
395 |
+
const sentiment = result.sentiment.toUpperCase();
|
396 |
+
const sentimentEmoji = sentiment === 'POSITIVE' ? 'π' :
|
397 |
+
sentiment === 'NEGATIVE' ? 'π' : 'π';
|
398 |
+
|
399 |
+
|
400 |
+
resultDiv.innerHTML = `
|
401 |
+
<div class="success-result">
|
402 |
+
<h4 class="font-semibold text-green-600 mb-2"> Sentiment Analysis</h4>
|
403 |
+
<div class="sentiment-result">
|
404 |
+
<p class="text-lg">${sentimentEmoji} <strong>${sentiment}</strong></p>
|
405 |
+
<p class="text-sm text-gray-600">Confidence: ${(result.confidence * 100).toFixed(1)}%</p>
|
406 |
+
<small class="text-gray-500">Model: ${result.model}</small>
|
407 |
+
</div>
|
408 |
+
</div>
|
409 |
+
`;
|
410 |
+
} else if (endpoint.includes('image')) {
|
411 |
+
resultDiv.innerHTML = `
|
412 |
+
<div class="success-result">
|
413 |
+
<h4 class="font-semibold text-green-600 mb-2">πΌοΈ Generated Image</h4>
|
414 |
+
<div class="image-result text-center">
|
415 |
+
<img src="data:image/png;base64,${result.image}"
|
416 |
+
alt="${result.prompt}"
|
417 |
+
class="w-full max-w-sm mx-auto rounded-lg shadow-md mb-2">
|
418 |
+
<p class="text-sm text-gray-600 italic">"${result.prompt}"</p>
|
419 |
+
<small class="text-gray-500">Model: ${result.model}</small>
|
420 |
+
</div>
|
421 |
+
</div>
|
422 |
+
`;
|
423 |
+
}
|
424 |
+
}
|
425 |
+
|
426 |
+
// Enhanced API call handler with proper x402 support
|
427 |
+
async function callApi(endpoint, data, buttonId, resultId) {
|
428 |
+
const button = document.getElementById(buttonId);
|
429 |
+
const resultDiv = document.getElementById(resultId);
|
430 |
+
|
431 |
+
button.disabled = true;
|
432 |
+
button.textContent = 'Processing...';
|
433 |
+
resultDiv.innerHTML = '<div class="loading">π Loading...</div>';
|
434 |
+
|
435 |
+
try {
|
436 |
+
const response = await fetch(endpoint, {
|
437 |
+
method: 'POST',
|
438 |
+
headers: {
|
439 |
+
'Content-Type': 'application/json',
|
440 |
+
'Accept': 'application/json'
|
441 |
+
},
|
442 |
+
body: JSON.stringify(data, (key, value) => {
|
443 |
+
// Handle BigInt values
|
444 |
+
if (typeof value === 'bigint') {
|
445 |
+
return value.toString();
|
446 |
+
}
|
447 |
+
return value;
|
448 |
+
})
|
449 |
+
});
|
450 |
+
|
451 |
+
// Handle 402 Payment Required - Create payment and retry
|
452 |
+
if (response.status === 402) {
|
453 |
+
const paymentInfo = await response.json();
|
454 |
+
|
455 |
+
if (!walletClient) {
|
456 |
+
resultDiv.innerHTML = `
|
457 |
+
<div class="payment-required">
|
458 |
+
<h4 class="text-lg font-semibold text-orange-600 mb-2">π³ Payment Required</h4>
|
459 |
+
<p class="text-sm text-gray-600 mb-2">Please connect your MetaMask wallet first.</p>
|
460 |
+
<div class="mt-3 p-3 bg-gray-50 rounded text-xs">
|
461 |
+
<p class="font-semibold mb-2">402 Response Details:</p>
|
462 |
+
<pre class="text-gray-700 overflow-x-auto">${JSON.stringify(paymentInfo, null, 2)}</pre>
|
463 |
+
</div>
|
464 |
+
<button onclick="connectWallet()" class="btn btn-primary text-sm mt-3">Connect Wallet</button>
|
465 |
+
</div>
|
466 |
+
`;
|
467 |
+
return;
|
468 |
+
}
|
469 |
+
|
470 |
+
try {
|
471 |
+
resultDiv.innerHTML = '<div class="loading">π³ Creating payment signature...</div>';
|
472 |
+
|
473 |
+
// Extract payment requirements from the first accept option
|
474 |
+
const paymentRequirements = paymentInfo.accepts[0];
|
475 |
+
|
476 |
+
// Create payment signature with retry logic for BigInt issues
|
477 |
+
let paymentHeader;
|
478 |
+
let attempts = 0;
|
479 |
+
const maxAttempts = 2;
|
480 |
+
|
481 |
+
while (attempts < maxAttempts) {
|
482 |
+
try {
|
483 |
+
paymentHeader = await createPaymentSignature(paymentRequirements);
|
484 |
+
break; // Success, exit retry loop
|
485 |
+
} catch (error) {
|
486 |
+
attempts++;
|
487 |
+
console.warn(`β οΈ Payment signature attempt ${attempts} failed:`, error.message);
|
488 |
+
|
489 |
+
if (error.message.includes('loop of type') || error.message.includes('bigint')) {
|
490 |
+
if (attempts < maxAttempts) {
|
491 |
+
console.log('π Retrying payment signature creation...');
|
492 |
+
await new Promise(resolve => setTimeout(resolve, 500)); // Wait before retry
|
493 |
+
continue;
|
494 |
+
}
|
495 |
+
}
|
496 |
+
throw error; // Re-throw if not a BigInt error or max attempts reached
|
497 |
+
}
|
498 |
+
}
|
499 |
+
|
500 |
+
// Ensure we have a valid payment header before proceeding
|
501 |
+
if (!paymentHeader) {
|
502 |
+
throw new Error('Failed to create payment signature');
|
503 |
+
}
|
504 |
+
|
505 |
+
resultDiv.innerHTML = '<div class="loading">π Processing payment...</div>';
|
506 |
+
|
507 |
+
console.log('π³ Sending payment request to:', endpoint);
|
508 |
+
console.log('π³ Payment header defined:', paymentHeader !== undefined);
|
509 |
+
console.log('π³ Payment header length:', paymentHeader?.length);
|
510 |
+
console.log('π³ Payment header preview:', paymentHeader?.substring(0, 100) + '...');
|
511 |
+
|
512 |
+
// Verify headers before sending
|
513 |
+
const requestHeaders = {
|
514 |
+
'Content-Type': 'application/json',
|
515 |
+
'Accept': 'application/json',
|
516 |
+
'X-Payment': paymentHeader
|
517 |
+
};
|
518 |
+
console.log('π³ Request headers:', requestHeaders);
|
519 |
+
|
520 |
+
// Retry the request with payment header
|
521 |
+
const paidResponse = await fetch(endpoint, {
|
522 |
+
method: 'POST',
|
523 |
+
headers: requestHeaders,
|
524 |
+
body: JSON.stringify(data, (key, value) => {
|
525 |
+
// Handle BigInt values
|
526 |
+
if (typeof value === 'bigint') {
|
527 |
+
console.warn('β οΈ Found BigInt in request body:', key, value);
|
528 |
+
return value.toString();
|
529 |
+
}
|
530 |
+
return value;
|
531 |
+
})
|
532 |
+
});
|
533 |
+
|
534 |
+
console.log('π³ Payment response status:', paidResponse.status);
|
535 |
+
console.log('π³ Payment response headers:', Object.fromEntries(paidResponse.headers.entries()));
|
536 |
+
|
537 |
+
if (!paidResponse.ok) {
|
538 |
+
const errorText = await paidResponse.text();
|
539 |
+
console.error('β Payment failed - response body:', errorText);
|
540 |
+
|
541 |
+
// If it's a 402, try to parse and show the specific validation error
|
542 |
+
if (paidResponse.status === 402) {
|
543 |
+
try {
|
544 |
+
const errorObj = JSON.parse(errorText);
|
545 |
+
console.error('β 402 Payment verification failed:', errorObj);
|
546 |
+
console.error('β Error message:', errorObj.error);
|
547 |
+
|
548 |
+
// Log the payment details for comparison
|
549 |
+
const sentPayload = JSON.parse(atob(paymentHeader));
|
550 |
+
console.error('β Sent payload:', sentPayload);
|
551 |
+
console.error('β Expected requirements:', errorObj.accepts?.[0]);
|
552 |
+
|
553 |
+
// Check for specific error patterns
|
554 |
+
if (errorObj.error) {
|
555 |
+
if (errorObj.error.includes('signature')) {
|
556 |
+
console.error('π SIGNATURE VERIFICATION FAILED');
|
557 |
+
} else if (errorObj.error.includes('nonce')) {
|
558 |
+
console.error('π NONCE ISSUE');
|
559 |
+
} else if (errorObj.error.includes('timing') || errorObj.error.includes('valid')) {
|
560 |
+
console.error('π TIMING ISSUE');
|
561 |
+
} else if (errorObj.error.includes('funds')) {
|
562 |
+
console.error('π INSUFFICIENT FUNDS');
|
563 |
+
} else {
|
564 |
+
console.error('π OTHER VALIDATION ERROR:', errorObj.error);
|
565 |
+
}
|
566 |
+
}
|
567 |
+
} catch (parseError) {
|
568 |
+
console.error('β Could not parse error response:', parseError);
|
569 |
+
}
|
570 |
+
}
|
571 |
+
|
572 |
+
let error;
|
573 |
+
try {
|
574 |
+
error = JSON.parse(errorText);
|
575 |
+
} catch {
|
576 |
+
error = { error: errorText };
|
577 |
+
}
|
578 |
+
|
579 |
+
throw new Error(error.detail || error.error || `Payment failed (${paidResponse.status})`);
|
580 |
+
}
|
581 |
+
|
582 |
+
// Payment successful, process the result
|
583 |
+
const result = await paidResponse.json();
|
584 |
+
displayResult(endpoint, result, resultDiv);
|
585 |
+
return;
|
586 |
+
|
587 |
+
} catch (paymentError) {
|
588 |
+
resultDiv.innerHTML = `
|
589 |
+
<div class="error-result">
|
590 |
+
<h4 class="font-semibold text-red-600 mb-2">π³ Payment Failed</h4>
|
591 |
+
<p class="text-red-700">${paymentError.message}</p>
|
592 |
+
<p class="text-sm text-gray-600 mt-2">Make sure you have testnet USDC on Base Sepolia.</p>
|
593 |
+
</div>
|
594 |
+
`;
|
595 |
+
return;
|
596 |
+
}
|
597 |
+
}
|
598 |
+
|
599 |
+
if (!response.ok) {
|
600 |
+
const error = await response.json();
|
601 |
+
throw new Error(error.detail || error.error || 'Request failed');
|
602 |
+
}
|
603 |
+
|
604 |
+
const result = await response.json();
|
605 |
+
displayResult(endpoint, result, resultDiv);
|
606 |
+
|
607 |
+
} catch (error) {
|
608 |
+
resultDiv.innerHTML = `
|
609 |
+
<div class="error-result">
|
610 |
+
<h4 class="font-semibold text-red-600 mb-2">β Error</h4>
|
611 |
+
<p class="text-red-700">${error.message}</p>
|
612 |
+
</div>
|
613 |
+
`;
|
614 |
+
} finally {
|
615 |
+
button.disabled = false;
|
616 |
+
if (button.id.includes('text')) {
|
617 |
+
button.textContent = 'Generate Text';
|
618 |
+
} else if (button.id.includes('sentiment')) {
|
619 |
+
button.textContent = 'Analyze Sentiment';
|
620 |
+
} else if (button.id.includes('image')) {
|
621 |
+
button.textContent = 'Generate Image';
|
622 |
+
}
|
623 |
+
}
|
624 |
+
}
|
625 |
+
|
626 |
+
// Event listeners
|
627 |
+
document.getElementById('text-btn').addEventListener('click', () => {
|
628 |
+
const prompt = document.getElementById('text-prompt').value.trim();
|
629 |
+
if (!prompt) {
|
630 |
+
alert('Please enter a prompt!');
|
631 |
+
return;
|
632 |
+
}
|
633 |
+
callApi('/generate-text', { prompt }, 'text-btn', 'text-result');
|
634 |
+
});
|
635 |
+
|
636 |
+
document.getElementById('sentiment-btn').addEventListener('click', () => {
|
637 |
+
const text = document.getElementById('sentiment-text').value.trim();
|
638 |
+
if (!text) {
|
639 |
+
alert('Please enter text to analyze!');
|
640 |
+
return;
|
641 |
+
}
|
642 |
+
callApi('/analyze-sentiment', { text }, 'sentiment-btn', 'sentiment-result');
|
643 |
+
});
|
644 |
+
|
645 |
+
document.getElementById('image-btn').addEventListener('click', () => {
|
646 |
+
const prompt = document.getElementById('image-prompt').value.trim();
|
647 |
+
if (!prompt) {
|
648 |
+
alert('Please enter an image prompt!');
|
649 |
+
return;
|
650 |
+
}
|
651 |
+
callApi('/generate-image', { prompt }, 'image-btn', 'image-result');
|
652 |
+
});
|
653 |
+
|
654 |
+
// Allow Enter key to submit
|
655 |
+
document.getElementById('text-prompt').addEventListener('keypress', (e) => {
|
656 |
+
if (e.key === 'Enter') document.getElementById('text-btn').click();
|
657 |
+
});
|
658 |
+
|
659 |
+
document.getElementById('image-prompt').addEventListener('keypress', (e) => {
|
660 |
+
if (e.key === 'Enter') document.getElementById('image-btn').click();
|
661 |
+
});
|
662 |
+
</script>
|
663 |
+
</body>
|
664 |
+
</html>
|