-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
243 lines (199 loc) · 7.45 KB
/
Copy pathmain.py
File metadata and controls
243 lines (199 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
import json
import re
import os
import datetime
from typing import List
try:
from llama_cpp import Llama
HAS_LLAMA = True
except ImportError:
HAS_LLAMA = False
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Actual GGUF model path provided by user
MODEL_PATH = r"C:\Users\swapn\Downloads\lifeosapk\mistral-7b-instruct-v0.2.Q4_K_M.gguf"
# Disabled legacy Llama-cpp so it doesn't compete with Ollama for RAM
llm = None
if False: # HAS_LLAMA and os.path.exists(MODEL_PATH):
try:
print(f"Loading Model from {MODEL_PATH}...")
llm = Llama(model_path=MODEL_PATH, n_ctx=2048, verbose=False)
print("Model loaded successfully.")
except Exception as e:
print(f"Warning: Failed to load Llama model. Error: {e}")
llm = None
else:
llm = None
if not os.path.exists(MODEL_PATH):
print(f"Warning: Model file not found at {MODEL_PATH}")
if not HAS_LLAMA:
print("Warning: llama-cpp-python not installed.")
print("Running in dummy fallback mode.")
class WorkoutItem(BaseModel):
exercise_name: str
weight_kg: float
reps: int
class TelemetryInput(BaseModel):
sleep_hours: float
steps: int
calories: int
money_spent: float
workouts: List[WorkoutItem]
class OutputResponse(BaseModel):
insight: str
recommendation: str
priority: str
class LifeOSModel:
def __init__(self, llm_instance=None):
self.llm = llm_instance
def generate(self, prompt: str) -> dict:
system_prompt = (
"You MUST return ONLY valid JSON.\n"
"No explanation.\n"
"No markdown.\n"
"No text before or after JSON.\n"
"Format exactly:\n"
'{"insight":"...","recommendation":"...","priority":"low|medium|high"}\n\n'
)
final_prompt = system_prompt + prompt
try:
import requests
payload = {
"model": "qwen3:8b",
"prompt": final_prompt,
"stream": False
}
# Increased timeout to 180s for slow hardware / initial model load
response = requests.post("http://localhost:11434/api/generate", json=payload, timeout=180)
response.raise_for_status()
res_json = response.json()
out_text = res_json.get("response", "").strip()
import re
match = re.search(r'\{.*\}', out_text, re.DOTALL)
if match:
json_str = match.group(0)
import json
data = json.loads(json_str)
return {
"insight": data.get("insight", "No insight parsed"),
"recommendation": data.get("recommendation", "No recommendation parsed"),
"priority": str(data.get("priority", "low")).lower()
}
else:
return self._fallback("Extraction failed.", out_text[:100] + "...")
except Exception as e:
print(f"Error from Ollama or Parsing: {e}")
return self._fallback("API/Parsing Error.", "An error occurred with Ollama.")
def _fallback(self, insight: str, rec: str) -> dict:
return {
"insight": insight,
"recommendation": rec,
"priority": "low"
}
LOGS_DIR = "logs"
LOG_FILE = os.path.join(LOGS_DIR, "daily.md")
def log_entry(input_data: TelemetryInput, output_data: dict):
if not os.path.exists(LOGS_DIR):
os.makedirs(LOGS_DIR)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
workouts_list = "\n".join([f" - {w.exercise_name}: {w.weight_kg}kg x {w.reps} reps" for w in input_data.workouts]) if input_data.workouts else " - None logged"
entry = f"""
## Entry - {timestamp}
**Input:**
- Sleep: {input_data.sleep_hours}
- Steps: {input_data.steps}
- Calories: {input_data.calories}
- Money Spent: {input_data.money_spent}
- Workouts:
{workouts_list}
**Output:**
- Insight: {output_data.get('insight', '')}
- Recommendation: {output_data.get('recommendation', '')}
- Priority: {output_data.get('priority', '')}
---
"""
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(entry)
def get_recent_entries(limit: int = 3) -> str:
if not os.path.exists(LOG_FILE):
return ""
try:
with open(LOG_FILE, "r", encoding="utf-8") as f:
content = f.read()
entries = content.split("## Entry -")
entries = [e for e in entries if e.strip()]
recent = entries[-limit:]
context = ""
for i, entry in enumerate(recent):
sleep_match = re.search(r"- Sleep:\s*([^\n]+)", entry)
steps_match = re.search(r"- Steps:\s*([^\n]+)", entry)
insight_match = re.search(r"- Insight:\s*([^\n]+)", entry)
rec_match = re.search(r"- Recommendation:\s*([^\n]+)", entry)
sleep = sleep_match.group(1).strip() if sleep_match else "N/A"
steps = steps_match.group(1).strip() if steps_match else "N/A"
insight = insight_match.group(1).strip() if insight_match else "N/A"
rec = rec_match.group(1).strip() if rec_match else "N/A"
context += f"Previous:\nSleep: {sleep}\nSteps: {steps}\nInsight: {insight}\nRecommendation: {rec}\n\n"
return context.strip()
except Exception as e:
print(f"Error reading logs: {e}")
return ""
@app.get("/")
def serve_frontend():
if os.path.exists("index.html"):
return FileResponse("index.html")
return {"message": "LifeOS API is running."}
@app.post("/analyze", response_model=OutputResponse)
def analyze(data: TelemetryInput):
workouts_list = "\n".join([f"- {w.exercise_name}: {w.weight_kg}kg x {w.reps} reps" for w in data.workouts])
if not workouts_list:
workouts_list = "None logged"
recent_context = get_recent_entries(3)
context_prompt = f"Recent History (for context):\n{recent_context}\n" if recent_context else ""
prompt = f"""You are an analytical system.
{context_prompt}
Input:
Sleep: {data.sleep_hours} hours
Steps: {data.steps}
Calories: {data.calories}
Money spent: {data.money_spent}
Workouts:
{workouts_list}
Rules:
- Use ALL inputs
- Consider the recent history for context on ongoing trends if available
- Identify patterns across health, effort, and spending
- Be specific, not generic
Output JSON:
{{
"insight": "...",
"recommendation": "...",
"priority": "low | medium | high"
}}"""
model = LifeOSModel(llm)
agent_res = model.generate(prompt)
raw_prio = agent_res.get("priority", "low").lower()
priority_map = {"low": 1, "medium": 2, "high": 3}
# normalize priority
if raw_prio not in priority_map:
raw_prio = "low"
output_dict = {
"insight": agent_res.get('insight', 'No insight generated'),
"recommendation": agent_res.get('recommendation', 'No recommendation generated'),
"priority": raw_prio
}
log_entry(data, output_dict)
return OutputResponse(**output_dict)
# Instructions to execute:
# pip install fastapi uvicorn llama-cpp-python pydantic
# uvicorn main:app --host 0.0.0.0 --port 8000 --reload