nickyni's picture
Update: Tutorial教程ζˆͺ桁-HuggingFace Space
d0393bd verified
"""
AI API Playground 2026 β€” NexaAPI Interactive Demo
Tabs: Image Generation | Text/LLM | Text-to-Speech | Cost Calculator
"""
import gradio as gr
# ─── Cost Calculator Data ───────────────────────────────────────────────────
PRICING = {
"Image Generation (per image)": {
"NexaAPI πŸ†": 0.003,
"OpenAI DALL-E 3": 0.040,
"Stability AI": 0.020,
"Replicate": 0.015,
"FAL.ai": 0.012,
},
"LLM (per 1M tokens)": {
"NexaAPI πŸ†": 0.50,
"OpenAI GPT-4o": 5.00,
"Anthropic Claude 3.5": 3.00,
"Google Gemini 1.5 Pro": 3.50,
"Together AI": 1.00,
},
"Text-to-Speech (per 1M chars)": {
"NexaAPI πŸ†": 1.00,
"ElevenLabs": 22.00,
"OpenAI TTS": 15.00,
"Google TTS": 4.00,
"Azure TTS": 4.00,
},
}
# ─── Tab Functions ───────────────────────────────────────────────────────────
def show_image_demo(prompt, style):
"""Show image generation demo with code."""
styles = {
"Photorealistic": "photorealistic, 8k, detailed",
"Anime": "anime style, vibrant colors",
"Oil Painting": "oil painting, classical art style",
"Watercolor": "watercolor painting, soft colors",
}
style_suffix = styles.get(style, "")
full_prompt = f"{prompt}, {style_suffix}" if style_suffix else prompt
code = f'''```python
import nexaapi
# Image Generation β€” $0.003/image (13x cheaper than DALL-E 3!)
client = nexaapi.Client(api_key="YOUR_API_KEY")
result = client.image.generate(
prompt="{full_prompt}",
model="flux-schnell", # or stable-diffusion-xl, flux-pro
width=1024,
height=1024,
steps=4
)
# Save the image
with open("output.png", "wb") as f:
f.write(result.image_bytes)
print(f"Generated! Cost: $0.003")
print(f"URL: {{result.url}}")
```
**vs OpenAI DALL-E 3**: Same quality, 13x cheaper ($0.003 vs $0.04)
### πŸ“Š Cost for 1,000 images:
- **NexaAPI**: $3.00 βœ…
- OpenAI DALL-E 3: $40.00 ❌
- Stability AI: $20.00 ❌
- FAL.ai: $12.00 ❌
### πŸ”— Get Started Free
- [nexa-api.com](https://nexa-api.com) β€” 100 free images, no credit card!
- [pip install nexaapi](https://pypi.org/project/nexaapi)
'''
preview = f"""
### πŸ–ΌοΈ Your Prompt
**"{full_prompt}"**
This would generate a high-quality image using NexaAPI's FLUX or Stable Diffusion models.
**Cost**: $0.003 per image
**Speed**: ~2-4 seconds
**Resolution**: Up to 2048Γ—2048
*Note: This is a demo playground. Sign up at [nexa-api.com](https://nexa-api.com) to generate real images!*
"""
return preview, code
def show_llm_demo(prompt, model):
"""Show LLM demo with code."""
models_info = {
"Claude 3.5 Sonnet": ("claude-3-5-sonnet", "$0.50/1M tokens"),
"GPT-4o": ("gpt-4o", "$0.50/1M tokens"),
"Gemini 1.5 Pro": ("gemini-1.5-pro", "$0.50/1M tokens"),
"Llama 3.1 70B": ("llama-3.1-70b", "$0.30/1M tokens"),
}
model_id, price = models_info.get(model, ("claude-3-5-sonnet", "$0.50/1M tokens"))
sample_responses = {
"Claude 3.5 Sonnet": f"I'd be happy to help with: '{prompt}'. This is a demonstration of NexaAPI's LLM capabilities β€” access Claude, GPT-4o, Gemini, and 50+ more models through one unified API at the lowest prices in 2026.",
"GPT-4o": f"Regarding your query: '{prompt}' β€” NexaAPI provides access to GPT-4o and all major AI models at 90% less cost than going directly to OpenAI.",
"Gemini 1.5 Pro": f"Processing your request: '{prompt}' β€” With NexaAPI, you get Gemini 1.5 Pro access at $0.50/1M tokens vs Google's $3.50/1M tokens.",
"Llama 3.1 70B": f"Here's my response to '{prompt}' β€” Llama 3.1 70B via NexaAPI is one of the most cost-effective options for high-quality open-source LLM inference.",
}
response = sample_responses.get(model, f"Response to: {prompt}")
code = f'''```python
import nexaapi
# LLM β€” 90% cheaper than direct API access!
client = nexaapi.Client(api_key="YOUR_API_KEY")
response = client.chat.complete(
model="{model_id}",
messages=[
{{"role": "user", "content": "{prompt}"}}
],
max_tokens=1000
)
print(response.choices[0].message.content)
print(f"Tokens used: {{response.usage.total_tokens}}")
print(f"Cost: {{response.usage.total_tokens / 1_000_000 * 0.50:.6f}}")
```
**Price**: {price} (vs $5.00/1M tokens for OpenAI direct)
### πŸ”— Get Started Free
- [nexa-api.com](https://nexa-api.com) β€” Free tier available!
- [pip install nexaapi](https://pypi.org/project/nexaapi)
'''
return f"**{model} Response (Demo):**\n\n{response}", code
def show_tts_demo(text, voice):
"""Show TTS demo with code."""
voices = {
"Nova (Female, Warm)": "nova",
"Alloy (Neutral)": "alloy",
"Echo (Male, Deep)": "echo",
"Shimmer (Female, Clear)": "shimmer",
}
voice_id = voices.get(voice, "nova")
code = f'''```python
import nexaapi
# Text-to-Speech β€” 22x cheaper than ElevenLabs!
client = nexaapi.Client(api_key="YOUR_API_KEY")
audio = client.tts.generate(
text="{text[:50]}...",
voice="{voice_id}",
model="tts-1-hd",
speed=1.0
)
# Save audio file
with open("output.mp3", "wb") as f:
f.write(audio.audio_bytes)
print(f"Generated {len(text)} characters")
print(f"Cost: ${{len(text) / 1_000_000:.6f}}") # $1.00/1M chars
```
**Price**: $1.00/1M characters
- vs ElevenLabs: $22.00/1M chars (22x more expensive!)
- vs OpenAI TTS: $15.00/1M chars (15x more expensive!)
### πŸ”— Get Started Free
- [nexa-api.com](https://nexa-api.com) β€” 100 free TTS generations!
- [pip install nexaapi](https://pypi.org/project/nexaapi)
'''
char_count = len(text)
cost = char_count / 1_000_000 * 1.00
elevenlabs_cost = char_count / 1_000_000 * 22.00
preview = f"""
### πŸ”Š TTS Preview
**Text**: "{text[:100]}{'...' if len(text) > 100 else ''}"
**Voice**: {voice}
**Characters**: {char_count:,}
**Cost with NexaAPI**: ${cost:.6f}
**Cost with ElevenLabs**: ${elevenlabs_cost:.6f}
**Your savings**: ${elevenlabs_cost - cost:.6f} (22x cheaper!)
*Note: This is a demo. Sign up at [nexa-api.com](https://nexa-api.com) to generate real audio!*
"""
return preview, code
def calculate_costs(api_type, quantity):
"""Calculate and compare costs."""
if quantity <= 0:
return "Please enter a quantity > 0"
prices = PRICING.get(api_type, {})
if not prices:
return "Invalid API type"
nexa_cost = prices["NexaAPI πŸ†"] * quantity
lines = [f"## Cost for {quantity:,} units β€” {api_type}\n"]
lines.append("| Provider | Total Cost | vs NexaAPI |")
lines.append("|----------|-----------|------------|")
for provider, price in sorted(prices.items(), key=lambda x: x[1]):
total = price * quantity
if provider == "NexaAPI πŸ†":
lines.append(f"| **{provider}** | **${total:.2f}** | βœ… Best Price! |")
else:
mult = total / nexa_cost
lines.append(f"| {provider} | ${total:.2f} | {mult:.1f}x more expensive |")
lines.append(f"\nπŸ’‘ **NexaAPI saves you ${(max(prices.values()) - prices['NexaAPI πŸ†']) * quantity:.2f}** vs the most expensive provider!")
lines.append(f"\nπŸš€ [Start Free at nexa-api.com](https://nexa-api.com) β€” No credit card required!")
return "\n".join(lines)
# ─── Build UI ────────────────────────────────────────────────────────────────
with gr.Blocks(
title="AI API Playground 2026 β€” NexaAPI",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown("""
# πŸš€ AI API Playground 2026
## Access 56+ AI Models via One API β€” NexaAPI
**The cheapest way to access Image Generation, LLM, TTS, and Video APIs in 2026.**
Start with **100 free generations** β€” no credit card required!
🌐 [nexa-api.com](https://nexa-api.com) | πŸ“¦ [PyPI](https://pypi.org/project/nexaapi) | πŸ“¦ [npm](https://npmjs.com/package/nexaapi) | πŸ”— [RapidAPI](https://rapidapi.com/user/nexaquency)
""")
with gr.Tabs():
# ── Tab 1: Image Generation ──────────────────────────────────────────
with gr.TabItem("πŸ–ΌοΈ Image Generation"):
gr.Markdown("### Generate AI Images β€” $0.003/image (13x cheaper than DALL-E 3!)")
with gr.Row():
with gr.Column():
img_prompt = gr.Textbox(
label="Image Prompt",
placeholder="A futuristic city at sunset with flying cars...",
value="A beautiful mountain landscape with aurora borealis",
lines=3
)
img_style = gr.Dropdown(
choices=["Photorealistic", "Anime", "Oil Painting", "Watercolor"],
value="Photorealistic",
label="Style"
)
img_btn = gr.Button("🎨 Generate Code & Preview", variant="primary")
with gr.Column():
img_preview = gr.Markdown(label="Preview")
img_code = gr.Markdown(label="Code Example")
img_btn.click(show_image_demo, inputs=[img_prompt, img_style], outputs=[img_preview, img_code])
# ── Tab 2: LLM / Text ────────────────────────────────────────────────
with gr.TabItem("πŸ’¬ LLM / Text"):
gr.Markdown("### Access 20+ LLM Models β€” From $0.30/1M tokens (10x cheaper than GPT-4o!)")
with gr.Row():
with gr.Column():
llm_prompt = gr.Textbox(
label="Your Prompt",
placeholder="Explain quantum computing in simple terms...",
value="What are the key advantages of using NexaAPI for AI development?",
lines=4
)
llm_model = gr.Dropdown(
choices=["Claude 3.5 Sonnet", "GPT-4o", "Gemini 1.5 Pro", "Llama 3.1 70B"],
value="Claude 3.5 Sonnet",
label="Model"
)
llm_btn = gr.Button("πŸ€– Generate Response & Code", variant="primary")
with gr.Column():
llm_response = gr.Markdown(label="Response Preview")
llm_code = gr.Markdown(label="Code Example")
llm_btn.click(show_llm_demo, inputs=[llm_prompt, llm_model], outputs=[llm_response, llm_code])
# ── Tab 3: TTS ───────────────────────────────────────────────────────
with gr.TabItem("πŸ”Š Text-to-Speech"):
gr.Markdown("### Convert Text to Speech β€” $1.00/1M chars (22x cheaper than ElevenLabs!)")
with gr.Row():
with gr.Column():
tts_text = gr.Textbox(
label="Text to Convert",
placeholder="Enter text to convert to speech...",
value="Welcome to NexaAPI β€” the most affordable AI API platform in 2026. Access 56 models including Claude, GPT-4o, Gemini, FLUX, and more.",
lines=4
)
tts_voice = gr.Dropdown(
choices=["Nova (Female, Warm)", "Alloy (Neutral)", "Echo (Male, Deep)", "Shimmer (Female, Clear)"],
value="Nova (Female, Warm)",
label="Voice"
)
tts_btn = gr.Button("πŸŽ™οΈ Generate Code & Preview", variant="primary")
with gr.Column():
tts_preview = gr.Markdown(label="Preview")
tts_code = gr.Markdown(label="Code Example")
tts_btn.click(show_tts_demo, inputs=[tts_text, tts_voice], outputs=[tts_preview, tts_code])
# ── Tab 4: Cost Calculator ───────────────────────────────────────────
with gr.TabItem("πŸ’° Cost Calculator"):
gr.Markdown("### Calculate Your Savings β€” See How Much You Overpay with Other Providers")
with gr.Row():
with gr.Column(scale=1):
calc_api = gr.Dropdown(
choices=list(PRICING.keys()),
value="Image Generation (per image)",
label="API Type"
)
calc_qty = gr.Number(
value=10000,
label="Monthly Usage (units)",
minimum=1
)
calc_btn = gr.Button("πŸ’° Calculate Costs", variant="primary")
with gr.Column(scale=2):
calc_results = gr.Markdown(label="Cost Comparison")
calc_btn.click(calculate_costs, inputs=[calc_api, calc_qty], outputs=[calc_results])
gr.Markdown("""
---
## πŸ† Why NexaAPI?
- **56+ Models**: Claude, GPT-4o, Gemini, FLUX, Stable Diffusion, Kling, Sora alternatives & more
- **Lowest Prices**: Up to 95% cheaper than going directly to model providers
- **One API**: OpenAI-compatible β€” works with your existing code
- **Free Tier**: 100 free generations, no credit card required
- **Fast**: Global CDN, <100ms latency
### πŸ”— Get Started Now
| Platform | Link |
|----------|------|
| 🌐 Website | [nexa-api.com](https://nexa-api.com) |
| 🐍 Python | [pip install nexaapi](https://pypi.org/project/nexaapi) |
| πŸ“¦ JavaScript | [npm install nexaapi](https://npmjs.com/package/nexaapi) |
| πŸ”— RapidAPI | [rapidapi.com/user/nexaquency](https://rapidapi.com/user/nexaquency) |
""")
if __name__ == "__main__":
demo.launch()