hpyapali commited on
Commit
dcf3d7e
Β·
verified Β·
1 Parent(s): 4c95cbf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -27
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
- # βœ… Authenticate model download
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}") # βœ… Log AI response
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
- response = requests.post(api_url, json=payload, headers={"Content-Type": "application/json"})
 
68
  response_data = response.json()
69
- event_id = response_data.get("event_id", None)
70
 
71
  if event_id:
72
  print(f"πŸ“‘ Received Event ID: {event_id}")
73
- return poll_for_response(event_id) # βœ… Call function to poll for AI response
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
- for _ in range(10): # βœ… Poll for up to 10 attempts
86
- try:
87
- time.sleep(3) # βœ… Wait before polling
88
 
89
- response = requests.get(result_url)
 
 
 
90
  response_data = response.json()
91
 
92
- if "data" in response_data:
93
- ai_response = response_data["data"][0] # βœ… Extract AI response
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)