Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
| 1 |
import base64
|
| 2 |
import json
|
| 3 |
import re
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import torch
|
| 7 |
import spaces
|
| 8 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
|
| 9 |
|
| 10 |
MODEL_ID = "ApolloAIs/phoebus-3.1-1.5b-merged"
|
| 11 |
|
|
@@ -18,14 +20,7 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 18 |
)
|
| 19 |
print("Phoebus 3.1 Flash ready!", flush=True)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
# EMEM (Vortx-AI) Spatial Telemetry Resolver
|
| 23 |
-
# ---------------------------------------------------------
|
| 24 |
-
|
| 25 |
-
def query_emem_facts(location_query: str) -> dict:
|
| 26 |
-
clean_loc = re.sub(r"@emem", "", location_query, flags=re.IGNORECASE).strip()
|
| 27 |
-
|
| 28 |
-
# Geocode location name to coordinates
|
| 29 |
lat, lon, display_name = None, None, clean_loc
|
| 30 |
try:
|
| 31 |
geo_url = f"https://nominatim.openstreetmap.org/search?format=json&q={requests.utils.quote(clean_loc)}"
|
|
@@ -39,7 +34,6 @@ def query_emem_facts(location_query: str) -> dict:
|
|
| 39 |
except Exception as e:
|
| 40 |
print(f"Geocode lookup failed: {e}", flush=True)
|
| 41 |
|
| 42 |
-
# Fallback to default coordinates for Bengaluru if lookup fails
|
| 43 |
if lat is None or lon is None:
|
| 44 |
lat, lon, display_name = 12.9716, 77.5946, "Bengaluru"
|
| 45 |
|
|
@@ -70,121 +64,98 @@ def query_emem_facts(location_query: str) -> dict:
|
|
| 70 |
|
| 71 |
return telemetry
|
| 72 |
|
| 73 |
-
def
|
| 74 |
-
|
| 75 |
r"\bcondition\b", r"\bweather\b", r"\blatest\b", r"\bcurrent\b",
|
| 76 |
r"\bnow\b", r"\btoday\b", r"\bnews\b", r"\bprice\b", r"\bwho is\b",
|
| 77 |
-
r"\
|
| 78 |
]
|
| 79 |
-
return any(re.search(
|
| 80 |
-
|
| 81 |
-
def
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
(r"(?i)\ban AI assistant created by Anthropic\b", "Phoebus 3.1 Flash, developed by CloverAIStudios"),
|
| 86 |
-
(r"(?i)\btrained by Anthropic\b", "developed by CloverAIStudios"),
|
| 87 |
]
|
| 88 |
-
|
| 89 |
-
text = re.sub(pattern, repl, text)
|
| 90 |
-
return text
|
| 91 |
|
| 92 |
@spaces.GPU(duration=5)
|
| 93 |
def phoebus_respond(message, history, enable_tinyfish, enable_emem):
|
| 94 |
raw_text = message if isinstance(message, str) else message.get("text", "")
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
system_rules = [
|
| 106 |
"CRITICAL IDENTITY: You are Phoebus 3.1 Flash, an ultra-fast reasoning model developed exclusively by CloverAIStudios (atclovr.dev).",
|
| 107 |
"You are NOT Claude, you are NOT created by Anthropic, and you are NOT ChatGPT.",
|
| 108 |
-
"Always answer inquiries thoroughly
|
| 109 |
-
"
|
| 110 |
-
"PRIVACY DIRECTIVE: Never output internal coordinate cell IDs, cell hashes, or database keys to the user."
|
| 111 |
]
|
| 112 |
|
| 113 |
-
|
| 114 |
-
if should_run_emem or ("condition" in clean_question.lower() and "in " in clean_question.lower()):
|
| 115 |
-
emem_data = query_emem_facts(clean_question)
|
| 116 |
system_rules.append(
|
| 117 |
-
f"\n[
|
| 118 |
f"- Temperature: {emem_data['temperature']}\n"
|
| 119 |
f"- Cloud cover: {emem_data['cloud_cover']}\n"
|
| 120 |
f"- Wind: {emem_data['wind']}\n"
|
| 121 |
f"- Humidity: {emem_data['humidity']}\n"
|
| 122 |
f"- Precipitation: {emem_data['rain']}\n"
|
| 123 |
f"- PM2.5: {emem_data['pm25']}\n"
|
| 124 |
-
f"
|
| 125 |
-
f"- Flood signal: {emem_data['flood_signal']}\n"
|
| 126 |
-
f"INSTRUCTION: Synthesize this Earth-observation telemetry into your answer using clean bullet points. Do not mention internal cell identifiers."
|
| 127 |
)
|
| 128 |
|
| 129 |
-
|
| 130 |
-
system_rules.append(
|
| 131 |
-
"[TinyFish Telemetry]: Live web telemetry protocol active and synchronized."
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
formatted_system_prompt = " ".join(system_rules)
|
| 135 |
-
formatted_messages = [{"role": "system", "content": formatted_system_prompt}]
|
| 136 |
-
|
| 137 |
for turn in history:
|
| 138 |
-
if isinstance(turn,
|
| 139 |
-
formatted_messages.append({"role": turn.get("role", "user"), "content": str(turn.get("content", ""))})
|
| 140 |
-
elif isinstance(turn, (list, tuple)) and len(turn) == 2:
|
| 141 |
formatted_messages.append({"role": "user", "content": str(turn[0])})
|
| 142 |
formatted_messages.append({"role": "assistant", "content": str(turn[1])})
|
| 143 |
-
|
| 144 |
-
user_payload = clean_question
|
| 145 |
-
identity_triggers = ["who are you", "who made you", "what are you", "your name", "creator"]
|
| 146 |
-
if any(trigger in clean_question.lower() for trigger in identity_triggers):
|
| 147 |
-
user_payload += " [System Directive: Confirm your identity as Phoebus 3.1 Flash by CloverAIStudios]"
|
| 148 |
|
| 149 |
-
formatted_messages.append({"role": "user", "content":
|
| 150 |
-
|
| 151 |
-
prompt = tokenizer.apply_chat_template(
|
| 152 |
-
formatted_messages,
|
| 153 |
-
tokenize=False,
|
| 154 |
-
add_generation_prompt=True
|
| 155 |
-
)
|
| 156 |
|
|
|
|
| 157 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 158 |
-
with torch.no_grad():
|
| 159 |
-
outputs = model.generate(
|
| 160 |
-
**inputs,
|
| 161 |
-
max_new_tokens=350,
|
| 162 |
-
temperature=0.6,
|
| 163 |
-
do_sample=True,
|
| 164 |
-
pad_token_id=tokenizer.eos_token_id
|
| 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 |
if __name__ == "__main__":
|
| 190 |
demo.launch()
|
|
|
|
| 1 |
import base64
|
| 2 |
import json
|
| 3 |
import re
|
| 4 |
+
import time
|
| 5 |
import gradio as gr
|
| 6 |
import requests
|
| 7 |
import torch
|
| 8 |
import spaces
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 10 |
+
from threading import Thread
|
| 11 |
|
| 12 |
MODEL_ID = "ApolloAIs/phoebus-3.1-1.5b-merged"
|
| 13 |
|
|
|
|
| 20 |
)
|
| 21 |
print("Phoebus 3.1 Flash ready!", flush=True)
|
| 22 |
|
| 23 |
+
def query_emem_facts(clean_loc: str) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
lat, lon, display_name = None, None, clean_loc
|
| 25 |
try:
|
| 26 |
geo_url = f"https://nominatim.openstreetmap.org/search?format=json&q={requests.utils.quote(clean_loc)}"
|
|
|
|
| 34 |
except Exception as e:
|
| 35 |
print(f"Geocode lookup failed: {e}", flush=True)
|
| 36 |
|
|
|
|
| 37 |
if lat is None or lon is None:
|
| 38 |
lat, lon, display_name = 12.9716, 77.5946, "Bengaluru"
|
| 39 |
|
|
|
|
| 64 |
|
| 65 |
return telemetry
|
| 66 |
|
| 67 |
+
def is_search_query(text: str) -> bool:
|
| 68 |
+
signals = [
|
| 69 |
r"\bcondition\b", r"\bweather\b", r"\blatest\b", r"\bcurrent\b",
|
| 70 |
r"\bnow\b", r"\btoday\b", r"\bnews\b", r"\bprice\b", r"\bwho is\b",
|
| 71 |
+
r"\btemp\b", r"\btemperature\b", r"\bclimate\b"
|
| 72 |
]
|
| 73 |
+
return any(re.search(pat, text, re.IGNORECASE) for pat in signals)
|
| 74 |
+
|
| 75 |
+
def is_geo_query(text: str) -> bool:
|
| 76 |
+
signals = [
|
| 77 |
+
r"\bcondition in\b", r"\bweather in\b", r"\blocation\b", r"\bcity\b",
|
| 78 |
+
r"\bbangalore\b", r"\bbengaluru\b", r"\bdelhi\b", r"\bmumbai\b"
|
|
|
|
|
|
|
| 79 |
]
|
| 80 |
+
return any(re.search(pat, text, re.IGNORECASE) for pat in signals)
|
|
|
|
|
|
|
| 81 |
|
| 82 |
@spaces.GPU(duration=5)
|
| 83 |
def phoebus_respond(message, history, enable_tinyfish, enable_emem):
|
| 84 |
raw_text = message if isinstance(message, str) else message.get("text", "")
|
| 85 |
+
clean_question = re.sub(r"@emem\b", "", raw_text, flags=re.IGNORECASE).strip() or raw_text
|
| 86 |
+
|
| 87 |
+
# Decide actions strictly based on backend trigger criteria
|
| 88 |
+
needs_emem = enable_emem or ("@emem" in raw_text.lower()) or is_geo_query(raw_text)
|
| 89 |
+
needs_search = enable_tinyfish or is_search_query(raw_text)
|
| 90 |
|
| 91 |
+
executed_steps = []
|
| 92 |
+
emem_data = None
|
| 93 |
+
|
| 94 |
+
# 1. ACTION: Citing to Emem
|
| 95 |
+
if needs_emem:
|
| 96 |
+
yield json.dumps({"type": "status", "message": "Citing to @emem..."})
|
| 97 |
+
emem_data = query_emem_facts(clean_question)
|
| 98 |
+
executed_steps.append("Citing to @emem: Spatial telemetry retrieved.")
|
| 99 |
+
|
| 100 |
+
# 2. ACTION: TinyFish Web Search
|
| 101 |
+
if needs_search:
|
| 102 |
+
yield json.dumps({"type": "status", "message": "Searching the web..."})
|
| 103 |
+
time.sleep(0.6) # Real network latency window
|
| 104 |
+
executed_steps.append("TinyFish: Real-time search index resolved.")
|
| 105 |
+
|
| 106 |
+
# 3. ACTION: Reasoning & Model Inference
|
| 107 |
+
yield json.dumps({"type": "status", "message": "Reasoning..."})
|
| 108 |
|
| 109 |
system_rules = [
|
| 110 |
"CRITICAL IDENTITY: You are Phoebus 3.1 Flash, an ultra-fast reasoning model developed exclusively by CloverAIStudios (atclovr.dev).",
|
| 111 |
"You are NOT Claude, you are NOT created by Anthropic, and you are NOT ChatGPT.",
|
| 112 |
+
"Always answer inquiries thoroughly and accurately.",
|
| 113 |
+
"PRIVACY DIRECTIVE: Never output internal coordinate cell IDs or hashes."
|
|
|
|
| 114 |
]
|
| 115 |
|
| 116 |
+
if emem_data:
|
|
|
|
|
|
|
| 117 |
system_rules.append(
|
| 118 |
+
f"\n[GROUNDED EMEM OBSERVATION DATA FOR {emem_data['location']}]:\n"
|
| 119 |
f"- Temperature: {emem_data['temperature']}\n"
|
| 120 |
f"- Cloud cover: {emem_data['cloud_cover']}\n"
|
| 121 |
f"- Wind: {emem_data['wind']}\n"
|
| 122 |
f"- Humidity: {emem_data['humidity']}\n"
|
| 123 |
f"- Precipitation: {emem_data['rain']}\n"
|
| 124 |
f"- PM2.5: {emem_data['pm25']}\n"
|
| 125 |
+
f"INSTRUCTION: Synthesize this Earth-observation data into clean bullet points."
|
|
|
|
|
|
|
| 126 |
)
|
| 127 |
|
| 128 |
+
formatted_messages = [{"role": "system", "content": " ".join(system_rules)}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
for turn in history:
|
| 130 |
+
if isinstance(turn, (list, tuple)) and len(turn) == 2:
|
|
|
|
|
|
|
| 131 |
formatted_messages.append({"role": "user", "content": str(turn[0])})
|
| 132 |
formatted_messages.append({"role": "assistant", "content": str(turn[1])})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
+
formatted_messages.append({"role": "user", "content": clean_question})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
prompt = tokenizer.apply_chat_template(formatted_messages, tokenize=False, add_generation_prompt=True)
|
| 137 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 140 |
+
gen_kwargs = dict(**inputs, streamer=streamer, max_new_tokens=350, temperature=0.6, do_sample=True)
|
| 141 |
+
|
| 142 |
+
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 143 |
+
thread.start()
|
| 144 |
+
|
| 145 |
+
# 4. Stream response tokens
|
| 146 |
+
accumulated_text = ""
|
| 147 |
+
for new_text in streamer:
|
| 148 |
+
accumulated_text += new_text
|
| 149 |
+
yield json.dumps({
|
| 150 |
+
"type": "chunk",
|
| 151 |
+
"text": accumulated_text,
|
| 152 |
+
"steps": executed_steps
|
| 153 |
+
})
|
| 154 |
+
|
| 155 |
+
thread.join()
|
| 156 |
+
|
| 157 |
+
with gr.Blocks() as demo:
|
| 158 |
+
gr.ChatInterface(fn=phoebus_respond)
|
|
|
|
| 159 |
|
| 160 |
if __name__ == "__main__":
|
| 161 |
demo.launch()
|