Spaces:
Sleeping
Sleeping
feat: add /story/image endpoint with Unsplash→Pexels→Pollinations fallback + image API keys in config
Browse filesFiles changed (4)
- .env.example+6
- app.py+59-3
- config.py+6
- static/js/stories-flashcards.js+34-12
13 unmodified lines14151617181913 unmodified linesGROQ_API_KEY=GROQ_API_KEYS=# Auth / local DBDATABASE_PATH=users.dbJWT_SECRET_KEY=replace_with_a_long_random_secret_min_32_chars13 unmodified lines14151617181920212223242513 unmodified linesGROQ_API_KEY=GROQ_API_KEYS=# Image APIs (story illustrations)UNSPLASH_ACCESS_KEY=PEXELS_API_KEY=IMGBB_API_KEY=POLLINATIONS_API_KEY=# Auth / local DBDATABASE_PATH=users.dbJWT_SECRET_KEY=replace_with_a_long_random_secret_min_32_chars
3 unmodified lines456789535 unmodified lines54554654754854955055155255330 unmodified lines5845855865875885893 unmodified linesimport jsonimport randomimport tempfilefrom collections import defaultdictfrom flask import (Flask,535 unmodified lineslevel = data.get("level", "intermediate")topic = data.get("topic", "daily life")lang_names = {"en": "English", "fr": "French", "es": "Spanish","de": "German", "ar": "Arabic", "it": "Italian","pt": "Portuguese", "ja": "Japanese", "zh": "Chinese",}lang_name = lang_names.get(language, "English")word_counts = {"beginner": 80, "intermediate": 130, "advanced": 180}30 unmodified linesreturn jsonify({"error": "Could not generate story"}), 500def get_welcome_message(topic="free", language="en", scenario=None):lang_config = Config.LANGUAGES.get(language, Config.LANGUAGES["en"])3 unmodified lines45678910535 unmodified lines54654754854955055155255355455555655755855956030 unmodified lines5915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446453 unmodified linesimport jsonimport randomimport tempfileimport requests as _httpfrom collections import defaultdictfrom flask import (Flask,535 unmodified lineslevel = data.get("level", "intermediate")topic = data.get("topic", "daily life")lang_names = {"en": "English","fr": "French","es": "Spanish","de": "German","ar": "Arabic","it": "Italian","pt": "Portuguese","ja": "Japanese","zh": "Chinese",}lang_name = lang_names.get(language, "English")word_counts = {"beginner": 80, "intermediate": 130, "advanced": 180}30 unmodified linesreturn jsonify({"error": "Could not generate story"}), 500@app.route("/story/image", methods=["POST"])def get_story_image():"""Fetch a relevant image from Unsplash → Pexels → Pollinations fallback chain."""data = request.json or {}topic = str(data.get("topic", ""))[:60]image_prompt = str(data.get("image_prompt", topic))[:80]query = topic or image_prompt# 1. Unsplash (highest quality, free API)if Config.UNSPLASH_ACCESS_KEY:try:r = _http.get("https://api.unsplash.com/photos/random",params={"query": query,"orientation": "landscape","count": 1,"content_filter": "high",},headers={"Authorization": f"Client-ID {Config.UNSPLASH_ACCESS_KEY}"},timeout=5,)if r.ok:photos = r.json()if isinstance(photos, list) and photos:return jsonify({"url": photos[0]["urls"]["regular"], "source": "unsplash"})except Exception as e:logging.warning(f"Unsplash image fetch failed: {e}")# 2. Pexels fallbackif Config.PEXELS_API_KEY:try:r = _http.get("https://api.pexels.com/v1/search",params={"query": query, "per_page": 1, "orientation": "landscape"},headers={"Authorization": Config.PEXELS_API_KEY},timeout=5,)if r.ok:d = r.json()if d.get("photos"):return jsonify({"url": d["photos"][0]["src"]["large"], "source": "pexels"})except Exception as e:logging.warning(f"Pexels image fetch failed: {e}")# 3. Signal client to use Pollinations (no server-side key needed)return jsonify({"url": None, "source": "pollinations"})def get_welcome_message(topic="free", language="en", scenario=None):lang_config = Config.LANGUAGES.get(language, Config.LANGUAGES["en"])
9 unmodified lines1011121314159 unmodified lines# --- API Keys ---NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")# Groq keys with rotation supportGROQ_API_KEYS = [k for k in [9 unmodified lines1011121314151617181920219 unmodified lines# --- API Keys ---NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")# Image API keysUNSPLASH_ACCESS_KEY = os.environ.get("UNSPLASH_ACCESS_KEY", "")PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY", "")IMGBB_API_KEY = os.environ.get("IMGBB_API_KEY", "")POLLINATIONS_API_KEY = os.environ.get("POLLINATIONS_API_KEY", "")# Groq keys with rotation supportGROQ_API_KEYS = [k for k in [
214 unmodified lines215216217218219220221222223224225226227228229230231232214 unmodified lines});}// Image via Pollinationsif (imgEl && data.image_prompt) {const imgUrl = pollinationsUrl(data.image_prompt);imgEl.onload = () => {if (shimmer) shimmer.classList.add('hidden');imgEl.classList.remove('hidden');};imgEl.onerror = () => {if (shimmer) shimmer.classList.add('hidden');};imgEl.src = imgUrl;imgEl.alt = data.title || 'Story illustration';} else {if (shimmer) shimmer.classList.add('hidden');}214 unmodified lines215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254214 unmodified lines});}// Image via backend (Unsplash → Pexels → Pollinations fallback)if (imgEl && (data.image_prompt || this.currentTopic)) {fetch('/story/image', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({topic: this.currentTopic,image_prompt: data.image_prompt || data.title || this.currentTopic,}),}).then((r) => r.json()).then((imgData) => {const url = imgData.url || pollinationsUrl(data.image_prompt || this.currentTopic);imgEl.alt = data.title || 'Story illustration';imgEl.onload = () => {if (shimmer) shimmer.classList.add('hidden');imgEl.classList.remove('hidden');};imgEl.onerror = () => {if (shimmer) shimmer.classList.add('hidden');};imgEl.src = url;}).catch(() => {// Pollinations client-side fallback on network errorconst url = pollinationsUrl(data.image_prompt || this.currentTopic);imgEl.alt = data.title || 'Story illustration';imgEl.onload = () => {if (shimmer) shimmer.classList.add('hidden');imgEl.classList.remove('hidden');};imgEl.onerror = () => { if (shimmer) shimmer.classList.add('hidden'); };imgEl.src = url;});} else {if (shimmer) shimmer.classList.add('hidden');}
.env.example+6
app.py+59-3
config.py+6
static/js/stories-flashcards.js+34-12