hpyapali commited on
Commit
f602d29
Β·
verified Β·
1 Parent(s): b954822

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -26
app.py CHANGED
@@ -8,7 +8,7 @@ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
8
  import uvicorn
9
  import asyncio
10
 
11
- # βœ… Load Hugging Face API Token Securely
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 restarts
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
- # βœ… AI Function - Processes and ranks workouts
 
37
  def analyze_workouts(last_workouts: str):
38
  """Generates AI-based workout rankings based on heart rate recovery."""
39
  if pipe is None:
40
- print("❌ AI model is not loaded.")
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, # Low randomness for structured responses
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
- response_text = result[0]["generated_text"].strip()
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) # Debug log
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()) # Generate event ID
105
 
106
  print(f"βœ… Processing AI Request - Event ID: {event_id}")
107
 
108
  response_text = analyze_workouts(last_workouts)
109
 
110
- # Store response for polling
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} # Return event_id for tracking
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 Endpoint (If Webhook Fails)
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)