Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,7 +8,7 @@ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
|
| 8 |
import uvicorn
|
| 9 |
import asyncio
|
| 10 |
|
| 11 |
-
# β
Load Hugging Face
|
| 12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
if not HF_TOKEN:
|
| 14 |
raise ValueError("β HF_TOKEN not found! Set it in Hugging Face Secrets.")
|
|
@@ -19,7 +19,7 @@ event_store = {} # Store AI responses with event_id
|
|
| 19 |
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
-
# β
Log server
|
| 23 |
print("π Restarting Hugging Face AI Model Server...")
|
| 24 |
|
| 25 |
# β
Load AI Model
|
|
@@ -33,18 +33,16 @@ except Exception as e:
|
|
| 33 |
print(f"β Error loading model: {e}")
|
| 34 |
pipe = None
|
| 35 |
|
| 36 |
-
|
|
|
|
| 37 |
def analyze_workouts(last_workouts: str):
|
| 38 |
"""Generates AI-based workout rankings based on heart rate recovery."""
|
| 39 |
if pipe is None:
|
| 40 |
-
|
| 41 |
-
return "β AI model not loaded."
|
| 42 |
|
| 43 |
if not last_workouts.strip():
|
| 44 |
-
print("β Empty workout data received!")
|
| 45 |
return "β No workout data provided."
|
| 46 |
|
| 47 |
-
# Structured instruction for better AI processing
|
| 48 |
instruction = (
|
| 49 |
"You are a fitness AI assistant. Rank the following workouts based on heart rate recovery after 2 minutes."
|
| 50 |
"\n\n### Ranking Rules:"
|
|
@@ -59,34 +57,24 @@ def analyze_workouts(last_workouts: str):
|
|
| 59 |
"\n4. Strength Training - HR dip: 18 bpm"
|
| 60 |
"\n5. Walking - HR dip: 12 bpm"
|
| 61 |
"\n6. Yoga - HR dip: 8 bpm"
|
| 62 |
-
"\n\nβ οΈ **DO NOT repeat input. DO NOT explain. ONLY return the ranking in this format.**"
|
| 63 |
)
|
| 64 |
|
| 65 |
try:
|
| 66 |
-
print(f"π¨ Sending prompt to AI:\n{instruction}")
|
| 67 |
-
|
| 68 |
result = pipe(
|
| 69 |
instruction,
|
| 70 |
max_new_tokens=250,
|
| 71 |
-
temperature=0.3,
|
| 72 |
top_p=0.9,
|
| 73 |
do_sample=True,
|
| 74 |
return_full_text=False
|
| 75 |
)
|
| 76 |
|
| 77 |
-
print(f"π RAW HF RESPONSE: {result}")
|
| 78 |
-
|
| 79 |
if not result or not result[0].get("generated_text", "").strip():
|
| 80 |
-
print("β AI Response is empty!")
|
| 81 |
return "β AI did not generate a valid response."
|
| 82 |
|
| 83 |
-
|
| 84 |
-
print(f"π AI Response after cleanup: {response_text}")
|
| 85 |
-
|
| 86 |
-
return response_text
|
| 87 |
|
| 88 |
except Exception as e:
|
| 89 |
-
print(f"β AI Processing Error: {e}")
|
| 90 |
return f"β Error generating workout recommendation: {str(e)}"
|
| 91 |
|
| 92 |
|
|
@@ -95,36 +83,34 @@ def analyze_workouts(last_workouts: str):
|
|
| 95 |
async def process_workout_request(request: Request):
|
| 96 |
try:
|
| 97 |
req_body = await request.json()
|
| 98 |
-
print("π© RAW REQUEST FROM HF:", req_body)
|
| 99 |
|
| 100 |
if "data" not in req_body or not isinstance(req_body["data"], list):
|
| 101 |
raise HTTPException(status_code=400, detail="Invalid request format: 'data' must be a list.")
|
| 102 |
|
| 103 |
last_workouts = req_body["data"][0]
|
| 104 |
-
event_id = str(uuid.uuid4())
|
| 105 |
|
| 106 |
print(f"β
Processing AI Request - Event ID: {event_id}")
|
| 107 |
|
| 108 |
response_text = analyze_workouts(last_workouts)
|
| 109 |
|
| 110 |
-
|
| 111 |
-
event_store[event_id] = response_text
|
| 112 |
|
| 113 |
-
# β
Send AI response to webhook if provided
|
| 114 |
webhook_url = req_body.get("webhook_url")
|
| 115 |
if webhook_url:
|
| 116 |
print(f"π‘ Sending response to Webhook: {webhook_url}")
|
| 117 |
async with httpx.AsyncClient() as client:
|
| 118 |
await client.post(webhook_url, json={"event_id": event_id, "data": [response_text]})
|
| 119 |
|
| 120 |
-
return {"event_id": event_id}
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
print(f"β Error processing request: {e}")
|
| 124 |
raise HTTPException(status_code=500, detail=str(e))
|
| 125 |
|
| 126 |
|
| 127 |
-
# β
Polling
|
| 128 |
@app.get("/gradio_api/poll/{event_id}")
|
| 129 |
async def poll(event_id: str):
|
| 130 |
"""Fetches stored AI response for a given event ID."""
|
|
@@ -160,6 +146,7 @@ iface = gr.Interface(
|
|
| 160 |
description="Enter workout data to analyze effectiveness, rank workouts, and receive improvement recommendations."
|
| 161 |
)
|
| 162 |
|
|
|
|
| 163 |
# β
Start Both FastAPI & Gradio
|
| 164 |
def start_gradio():
|
| 165 |
iface.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|
|
| 8 |
import uvicorn
|
| 9 |
import asyncio
|
| 10 |
|
| 11 |
+
# β
Securely Load Hugging Face Token
|
| 12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
if not HF_TOKEN:
|
| 14 |
raise ValueError("β HF_TOKEN not found! Set it in Hugging Face Secrets.")
|
|
|
|
| 19 |
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
+
# β
Log server restart
|
| 23 |
print("π Restarting Hugging Face AI Model Server...")
|
| 24 |
|
| 25 |
# β
Load AI Model
|
|
|
|
| 33 |
print(f"β Error loading model: {e}")
|
| 34 |
pipe = None
|
| 35 |
|
| 36 |
+
|
| 37 |
+
# β
AI Function - Analyzes workout data
|
| 38 |
def analyze_workouts(last_workouts: str):
|
| 39 |
"""Generates AI-based workout rankings based on heart rate recovery."""
|
| 40 |
if pipe is None:
|
| 41 |
+
return "β AI model is not loaded."
|
|
|
|
| 42 |
|
| 43 |
if not last_workouts.strip():
|
|
|
|
| 44 |
return "β No workout data provided."
|
| 45 |
|
|
|
|
| 46 |
instruction = (
|
| 47 |
"You are a fitness AI assistant. Rank the following workouts based on heart rate recovery after 2 minutes."
|
| 48 |
"\n\n### Ranking Rules:"
|
|
|
|
| 57 |
"\n4. Strength Training - HR dip: 18 bpm"
|
| 58 |
"\n5. Walking - HR dip: 12 bpm"
|
| 59 |
"\n6. Yoga - HR dip: 8 bpm"
|
|
|
|
| 60 |
)
|
| 61 |
|
| 62 |
try:
|
|
|
|
|
|
|
| 63 |
result = pipe(
|
| 64 |
instruction,
|
| 65 |
max_new_tokens=250,
|
| 66 |
+
temperature=0.3,
|
| 67 |
top_p=0.9,
|
| 68 |
do_sample=True,
|
| 69 |
return_full_text=False
|
| 70 |
)
|
| 71 |
|
|
|
|
|
|
|
| 72 |
if not result or not result[0].get("generated_text", "").strip():
|
|
|
|
| 73 |
return "β AI did not generate a valid response."
|
| 74 |
|
| 75 |
+
return result[0]["generated_text"].strip()
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
except Exception as e:
|
|
|
|
| 78 |
return f"β Error generating workout recommendation: {str(e)}"
|
| 79 |
|
| 80 |
|
|
|
|
| 83 |
async def process_workout_request(request: Request):
|
| 84 |
try:
|
| 85 |
req_body = await request.json()
|
| 86 |
+
print("π© RAW REQUEST FROM HF:", req_body)
|
| 87 |
|
| 88 |
if "data" not in req_body or not isinstance(req_body["data"], list):
|
| 89 |
raise HTTPException(status_code=400, detail="Invalid request format: 'data' must be a list.")
|
| 90 |
|
| 91 |
last_workouts = req_body["data"][0]
|
| 92 |
+
event_id = str(uuid.uuid4())
|
| 93 |
|
| 94 |
print(f"β
Processing AI Request - Event ID: {event_id}")
|
| 95 |
|
| 96 |
response_text = analyze_workouts(last_workouts)
|
| 97 |
|
| 98 |
+
event_store[event_id] = response_text
|
|
|
|
| 99 |
|
|
|
|
| 100 |
webhook_url = req_body.get("webhook_url")
|
| 101 |
if webhook_url:
|
| 102 |
print(f"π‘ Sending response to Webhook: {webhook_url}")
|
| 103 |
async with httpx.AsyncClient() as client:
|
| 104 |
await client.post(webhook_url, json={"event_id": event_id, "data": [response_text]})
|
| 105 |
|
| 106 |
+
return {"event_id": event_id}
|
| 107 |
|
| 108 |
except Exception as e:
|
| 109 |
print(f"β Error processing request: {e}")
|
| 110 |
raise HTTPException(status_code=500, detail=str(e))
|
| 111 |
|
| 112 |
|
| 113 |
+
# β
Polling API (If Webhook Fails)
|
| 114 |
@app.get("/gradio_api/poll/{event_id}")
|
| 115 |
async def poll(event_id: str):
|
| 116 |
"""Fetches stored AI response for a given event ID."""
|
|
|
|
| 146 |
description="Enter workout data to analyze effectiveness, rank workouts, and receive improvement recommendations."
|
| 147 |
)
|
| 148 |
|
| 149 |
+
|
| 150 |
# β
Start Both FastAPI & Gradio
|
| 151 |
def start_gradio():
|
| 152 |
iface.launch(server_name="0.0.0.0", server_port=7860, share=True)
|