Spaces:
Running
Running
Update app.py
Browse files1234567817 unmodified lines2627282930313233341 unmodified line363738394041424344454681 unmodified lines1281291301311321331343 unmodified lines1381391401411421431441451461471481491501511521537 unmodified lines16116216316416516616716816917017117217333 unmodified lines20720820921021121221321421521625 unmodified lines24224324424524624724824925025125225325425525614 unmodified lines2712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183191 unmodified line3213223233243253263273283293303313323333343353363373383393403413423433443451 unmodified line34734834935035135213 unmodified lines366367368369import osimport sysimport jsonimport uuidimport hmacimport threadingimport importlib.util17 unmodified linesPENALTY = 1.2TEMPERATURE = 1.0# Poe sends this as "Authorization: Bearer <key>" on every request.# Set it as a Secret in your Hugging Face Space (POE_ACCESS_KEY).# If unset, Poe requests are accepted without auth (fine for testing only).POE_ACCESS_KEY = os.environ.get("POE_ACCESS_KEY", "")POE_INTRO_MESSAGE = "Hi! I'm Aoban Luna 2 Flash. Say something."1 unmodified lineapp = Flask(__name__)CORS(app)# Protect shared model inference and session history.generation_lock = threading.Lock()sessions = {}# ============================================================# Load Luna 2's custom architecture# ============================================================81 unmodified lines# ============================================================def sse(event, data):"""Format one Server-Sent Event the way Poe expects."""return f"event: {event}\ndata: {json.dumps(data)}\n\n"3 unmodified linesheader = request.headers.get("Authorization", "")token = header[7:] if header.lower().startswith("bearer ") else ""return hmac.compare_digest(token, POE_ACCESS_KEY)def poe_to_luna_history(query):"""Poe sends the FULL conversation on every request, so Poe bots arestateless. Convert it to (prompt, history) in Luna's format.Poe roles: "system" | "user" | "bot"Luna roles: "user" | "assistant""""messages = []7 unmodified linesif not isinstance(content, str) or not content.strip():continueif role == "user":messages.append({"role": "user", "content": content.strip()})elif role == "bot":messages.append({"role": "assistant", "content": content.strip()})# "system" messages are ignored; Luna has no system prompt.# The prompt is the latest user message; everything before it is history.prompt = ""history = []33 unmodified linesyield sse("text", {"text": response})except Exception as e:app.logger.exception("Luna generation failed (Poe)")yield sse("error", {"text": f"Brain Error: {e}","allow_retry": True})25 unmodified lines"introduction_message": POE_INTRO_MESSAGE})# "report_feedback" and "report_error" just need a 200 JSON reply.return jsonify({})# ============================================================# Poe endpoint + health check (same URL: "/")# ============================================================# Poe POSTs to the bot URL you register (the Space's root URL).# The browser/health check keeps using GET on the same route.@app.route("/", methods=["GET", "POST"])def root():14 unmodified lines# ============================================================# Chat endpoint (website / your JS script) - unchanged# ============================================================@app.route("/ask", methods=["POST"])def ask():try:data = request.get_json(silent=True)if not isinstance(data, dict):return jsonify({"response": "Invalid request body.","logs": "Expected a JSON object."}), 400prompt = data.get("input", "")if not isinstance(prompt, str):return jsonify({"response": "Input must be text.","logs": "Invalid input type."}), 400prompt = prompt.strip()if not prompt:return jsonify({"response": "Please enter a message.","logs": "Empty input."}), 400session_id = str(data.get("session_id") or uuid.uuid4())with generation_lock:history = sessions.setdefault(session_id, [])response = generate_response(prompt, list(history))history.extend([{"role": "user", "content": prompt},{"role": "assistant", "content": response}])print(f"[Bridge] Generated response for session {session_id[:8]}")return jsonify({"response": response,1 unmodified line"logs": "Generation successful."})except Exception as e:app.logger.exception("Luna generation failed")return jsonify({"response": f"Brain Error: {str(e)}","logs": str(e)}), 500# ============================================================# Clear conversation history - unchanged# ============================================================@app.route("/clear", methods=["POST"])def clear_history():data = request.get_json(silent=True) or {}session_id = data.get("session_id")if not isinstance(session_id, str) or not session_id.strip():return jsonify({"error": "Missing or invalid session_id."}), 4001 unmodified linewith generation_lock:sessions.pop(session_id, None)return jsonify({"status": "History cleared.","session_id": session_id13 unmodified lineshost="0.0.0.0",port=port,threaded=True)1234567891017 unmodified lines2829303132333435363738391 unmodified line4142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949581 unmodified lines1771781791801811821833 unmodified lines1871881891901911921931941951961971981992002012027 unmodified lines21021121221321421521621721821922022122222322422522622722822933 unmodified lines26326426526626726826927027127227325 unmodified lines29930030130230330430530630730830931031114 unmodified lines3263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933941 unmodified line3963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294301 unmodified line43243343443543643743843913 unmodified lines453454455456import osimport sysimport jsonimport uuidimport hmacimport timeimport threadingimport importlib.util17 unmodified linesPENALTY = 1.2TEMPERATURE = 1.0# Website conversations expire after 10 minutes of inactivity.# Browser-side cleanup should normally clear them much sooner.SESSION_TTL_SECONDS = 600# Optional Poe authentication.# Configure POE_ACCESS_KEY as a Hugging Face Space Secret.POE_ACCESS_KEY = os.environ.get("POE_ACCESS_KEY", "")POE_INTRO_MESSAGE = "Hi! I'm Aoban Luna 2 Flash. Say something."1 unmodified lineapp = Flask(__name__)CORS(app)# Protect shared model inference and website conversation history.generation_lock = threading.Lock()# Website sessions:# {# session_id: {# "history": [...],# "last_seen": timestamp# }# }sessions = {}# ============================================================# Session management# ============================================================def cleanup_expired_sessions():"""Remove website sessions that have been inactive too long."""now = time.time()expired_ids = [session_idfor session_id, session in sessions.items()if now - session["last_seen"] > SESSION_TTL_SECONDS]for session_id in expired_ids:sessions.pop(session_id, None)if expired_ids:print(f"[Bridge] Expired {len(expired_ids)} inactive session(s).")def get_session(session_id):"""Return an existing active session or create a new one."""now = time.time()session = sessions.get(session_id)if session is None or now - session["last_seen"] > SESSION_TTL_SECONDS:session = {"history": [],"last_seen": now}sessions[session_id] = sessionsession["last_seen"] = nowreturn session# ============================================================# Load Luna 2's custom architecture# ============================================================81 unmodified lines# ============================================================def sse(event, data):"""Format one Server-Sent Event for Poe."""return f"event: {event}\ndata: {json.dumps(data)}\n\n"3 unmodified linesheader = request.headers.get("Authorization", "")token = header[7:] if header.lower().startswith("bearer ") else ""return hmac.compare_digest(token, POE_ACCESS_KEY)def poe_to_luna_history(query):"""Poe sends the full conversation on each request.Poe roles: system, user, botLuna roles: user, assistant"""messages = []7 unmodified linesif not isinstance(content, str) or not content.strip():continuecontent = content.strip()if role == "user":messages.append({"role": "user","content": content})elif role == "bot":messages.append({"role": "assistant","content": content})# Use the latest user message as the prompt.prompt = ""history = []33 unmodified linesyield sse("text", {"text": response})except Exception:app.logger.exception("Luna generation failed (Poe)")yield sse("error", {"text": "Luna encountered an error while generating a response.","allow_retry": True})25 unmodified lines"introduction_message": POE_INTRO_MESSAGE})# Feedback and error reports require a successful response.return jsonify({})# ============================================================# Poe endpoint and health check# ============================================================@app.route("/", methods=["GET", "POST"])def root():14 unmodified lines# ============================================================# Website chat endpoint# ============================================================@app.route("/ask", methods=["POST"])def ask():data = request.get_json(silent=True)if not isinstance(data, dict):return jsonify({"response": "Invalid request body.","logs": "Expected a JSON object."}), 400prompt = data.get("input", "")if not isinstance(prompt, str):return jsonify({"response": "Input must be text.","logs": "Invalid input type."}), 400prompt = prompt.strip()if not prompt:return jsonify({"response": "Please enter a message.","logs": "Empty input."}), 400supplied_session_id = data.get("session_id")if supplied_session_id is not None and (not isinstance(supplied_session_id, str)or len(supplied_session_id) > 128or not supplied_session_id.strip()):return jsonify({"response": "Invalid session ID.","logs": "The session ID must be a non-empty string."}), 400session_id = supplied_session_id or str(uuid.uuid4())try:with generation_lock:cleanup_expired_sessions()session = get_session(session_id)history = list(session["history"])response = generate_response(prompt, history)session["history"].extend([{"role": "user", "content": prompt},{"role": "assistant", "content": response}])session["last_seen"] = time.time()print(f"[Bridge] Generated website response for "f"session {session_id[:8]}")return jsonify({"response": response,1 unmodified line"logs": "Generation successful."})except Exception:app.logger.exception("Luna generation failed (website)")return jsonify({"response": "Brain Error: Luna failed to generate a response.","logs": "Check the server logs for the full traceback."}), 500# ============================================================# Clear website conversation history# ============================================================@app.route("/clear", methods=["POST"])def clear_history():data = request.get_json(silent=True)if not isinstance(data, dict):return jsonify({"error": "Expected a JSON object."}), 400session_id = data.get("session_id")if (not isinstance(session_id, str)or not session_id.strip()or len(session_id) > 128):return jsonify({"error": "Missing or invalid session_id."}), 4001 unmodified linewith generation_lock:sessions.pop(session_id, None)print(f"[Bridge] Cleared website session {session_id[:8]}")return jsonify({"status": "History cleared.","session_id": session_id13 unmodified lineshost="0.0.0.0",port=port,threaded=True)
app.py+139-52