Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,22 +9,22 @@ MODEL_NAME = "hpyapali/tinyllama-workout"
|
|
| 9 |
# β
Retrieve API key from environment variable or manually set for debugging
|
| 10 |
HF_TOKEN = os.getenv("HF_TOKEN", "your_huggingface_api_key")
|
| 11 |
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
-
|
| 14 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 15 |
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 16 |
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
|
|
|
| 17 |
except Exception as e:
|
| 18 |
print(f"β Error loading model: {e}")
|
| 19 |
-
pipe = None
|
| 20 |
|
| 21 |
-
|
| 22 |
-
# β
Function to process AI workout recommendation
|
| 23 |
def workout_recommendation(prompt):
|
| 24 |
if pipe is None:
|
| 25 |
return ["β Model failed to load. Check API key and model availability."]
|
| 26 |
|
| 27 |
-
# β
Instruction to ensure AI returns only a structured workout recommendation
|
| 28 |
instruction = (
|
| 29 |
"You are a fitness AI assistant. Based on the provided past 7 workouts, "
|
| 30 |
"generate the best next workout. Only provide the next workout plan. "
|
|
@@ -37,78 +37,80 @@ def workout_recommendation(prompt):
|
|
| 37 |
)
|
| 38 |
|
| 39 |
full_prompt = instruction + "\n\nUser Workouts:\n" + prompt + "\n\nNext Workout:"
|
| 40 |
-
|
| 41 |
try:
|
| 42 |
result = pipe(full_prompt, max_new_tokens=150, do_sample=True)
|
| 43 |
response_text = result[0]["generated_text"].strip()
|
| 44 |
|
| 45 |
-
# β
Extract only the AI's response
|
| 46 |
if "Workout Type:" in response_text:
|
| 47 |
response_text = response_text.split("Workout Type:")[1]
|
| 48 |
response_text = "Workout Type: " + response_text.strip()
|
| 49 |
|
| 50 |
-
# β
Ensure the AI doesn't return duplicate input
|
| 51 |
if "User Workouts:" in response_text:
|
| 52 |
response_text = response_text.split("User Workouts:")[0].strip()
|
| 53 |
|
| 54 |
-
print(f"β
AI Recommendation: {response_text}")
|
| 55 |
return [response_text]
|
| 56 |
except Exception as e:
|
| 57 |
print(f"β AI Processing Error: {e}")
|
| 58 |
return ["β Error generating workout recommendation."]
|
| 59 |
|
| 60 |
-
|
| 61 |
-
# β
Function to handle POST request to Hugging Face API
|
| 62 |
def send_request_to_huggingface(prompt):
|
| 63 |
api_url = "https://hpyapali-tinyllama-workout.hf.space/gradio_api/call/predict"
|
| 64 |
payload = {"data": [prompt]}
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
-
|
|
|
|
| 68 |
response_data = response.json()
|
| 69 |
-
event_id = response_data.get("event_id"
|
| 70 |
|
| 71 |
if event_id:
|
| 72 |
print(f"π‘ Received Event ID: {event_id}")
|
| 73 |
-
return poll_for_response(event_id)
|
| 74 |
else:
|
| 75 |
return ["β No event ID received."]
|
| 76 |
except Exception as e:
|
| 77 |
print(f"β API Request Error: {e}")
|
| 78 |
return ["β Error sending request."]
|
| 79 |
|
| 80 |
-
|
| 81 |
# β
Function to poll AI response using event ID
|
| 82 |
def poll_for_response(event_id):
|
| 83 |
result_url = f"https://hpyapali-tinyllama-workout.hf.space/gradio_api/call/predict/{event_id}"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
time.sleep(3) # β
Wait before polling
|
| 88 |
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
| 90 |
response_data = response.json()
|
| 91 |
|
| 92 |
-
if "data" in response_data:
|
| 93 |
-
ai_response = response_data["data"][0]
|
| 94 |
print(f"π¨ AI Response: {ai_response}")
|
| 95 |
-
|
| 96 |
return [ai_response]
|
| 97 |
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
print(f"β οΈ Error polling AI response: {e}")
|
| 100 |
|
| 101 |
return ["β AI response not received."]
|
| 102 |
|
| 103 |
-
|
| 104 |
# β
Gradio API Interface
|
| 105 |
iface = gr.Interface(
|
| 106 |
fn=send_request_to_huggingface,
|
| 107 |
inputs="text",
|
| 108 |
outputs="text",
|
| 109 |
title="TinyLlama Workout Recommendations",
|
| 110 |
-
description="Enter a prompt to receive a structured workout recommendation."
|
|
|
|
| 111 |
)
|
| 112 |
|
| 113 |
-
# β
Fix: Removed `enable_queue=True` since it's not needed
|
| 114 |
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 9 |
# β
Retrieve API key from environment variable or manually set for debugging
|
| 10 |
HF_TOKEN = os.getenv("HF_TOKEN", "your_huggingface_api_key")
|
| 11 |
|
| 12 |
+
# β
Load Model
|
| 13 |
+
pipe = None
|
| 14 |
try:
|
| 15 |
+
print("π Loading Model...")
|
| 16 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 17 |
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 18 |
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 19 |
+
print("β
Model Loaded Successfully!")
|
| 20 |
except Exception as e:
|
| 21 |
print(f"β Error loading model: {e}")
|
|
|
|
| 22 |
|
| 23 |
+
# β
Function to generate AI workout recommendations
|
|
|
|
| 24 |
def workout_recommendation(prompt):
|
| 25 |
if pipe is None:
|
| 26 |
return ["β Model failed to load. Check API key and model availability."]
|
| 27 |
|
|
|
|
| 28 |
instruction = (
|
| 29 |
"You are a fitness AI assistant. Based on the provided past 7 workouts, "
|
| 30 |
"generate the best next workout. Only provide the next workout plan. "
|
|
|
|
| 37 |
)
|
| 38 |
|
| 39 |
full_prompt = instruction + "\n\nUser Workouts:\n" + prompt + "\n\nNext Workout:"
|
| 40 |
+
|
| 41 |
try:
|
| 42 |
result = pipe(full_prompt, max_new_tokens=150, do_sample=True)
|
| 43 |
response_text = result[0]["generated_text"].strip()
|
| 44 |
|
|
|
|
| 45 |
if "Workout Type:" in response_text:
|
| 46 |
response_text = response_text.split("Workout Type:")[1]
|
| 47 |
response_text = "Workout Type: " + response_text.strip()
|
| 48 |
|
|
|
|
| 49 |
if "User Workouts:" in response_text:
|
| 50 |
response_text = response_text.split("User Workouts:")[0].strip()
|
| 51 |
|
| 52 |
+
print(f"β
AI Recommendation: {response_text}")
|
| 53 |
return [response_text]
|
| 54 |
except Exception as e:
|
| 55 |
print(f"β AI Processing Error: {e}")
|
| 56 |
return ["β Error generating workout recommendation."]
|
| 57 |
|
| 58 |
+
# β
Function to send request to Hugging Face API
|
|
|
|
| 59 |
def send_request_to_huggingface(prompt):
|
| 60 |
api_url = "https://hpyapali-tinyllama-workout.hf.space/gradio_api/call/predict"
|
| 61 |
payload = {"data": [prompt]}
|
| 62 |
+
headers = {
|
| 63 |
+
"Content-Type": "application/json",
|
| 64 |
+
"Authorization": f"Bearer {HF_TOKEN}", # β
Ensure API key is sent
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
try:
|
| 68 |
+
print(f"π€ Sending API Request: {prompt}")
|
| 69 |
+
response = requests.post(api_url, json=payload, headers=headers)
|
| 70 |
response_data = response.json()
|
| 71 |
+
event_id = response_data.get("event_id")
|
| 72 |
|
| 73 |
if event_id:
|
| 74 |
print(f"π‘ Received Event ID: {event_id}")
|
| 75 |
+
return poll_for_response(event_id)
|
| 76 |
else:
|
| 77 |
return ["β No event ID received."]
|
| 78 |
except Exception as e:
|
| 79 |
print(f"β API Request Error: {e}")
|
| 80 |
return ["β Error sending request."]
|
| 81 |
|
|
|
|
| 82 |
# β
Function to poll AI response using event ID
|
| 83 |
def poll_for_response(event_id):
|
| 84 |
result_url = f"https://hpyapali-tinyllama-workout.hf.space/gradio_api/call/predict/{event_id}"
|
| 85 |
+
headers = {
|
| 86 |
+
"Authorization": f"Bearer {HF_TOKEN}", # β
Ensure API key is sent
|
| 87 |
+
}
|
|
|
|
| 88 |
|
| 89 |
+
for attempt in range(1, 21): # β
Poll up to 20 times
|
| 90 |
+
try:
|
| 91 |
+
time.sleep(3)
|
| 92 |
+
response = requests.get(result_url, headers=headers)
|
| 93 |
response_data = response.json()
|
| 94 |
|
| 95 |
+
if "data" in response_data and response_data["data"]:
|
| 96 |
+
ai_response = response_data["data"][0]
|
| 97 |
print(f"π¨ AI Response: {ai_response}")
|
|
|
|
| 98 |
return [ai_response]
|
| 99 |
|
| 100 |
+
print(f"β οΈ AI response not ready, retrying (Attempt {attempt}/20)...")
|
| 101 |
except Exception as e:
|
| 102 |
print(f"β οΈ Error polling AI response: {e}")
|
| 103 |
|
| 104 |
return ["β AI response not received."]
|
| 105 |
|
|
|
|
| 106 |
# β
Gradio API Interface
|
| 107 |
iface = gr.Interface(
|
| 108 |
fn=send_request_to_huggingface,
|
| 109 |
inputs="text",
|
| 110 |
outputs="text",
|
| 111 |
title="TinyLlama Workout Recommendations",
|
| 112 |
+
description="Enter a prompt to receive a structured workout recommendation.",
|
| 113 |
+
enable_queue=True # β
Fix: Allow multiple requests in a queue
|
| 114 |
)
|
| 115 |
|
|
|
|
| 116 |
iface.launch(server_name="0.0.0.0", server_port=7860)
|