ScratchWeb / app.py
WillemVH's picture
Update app.py
12e6780 verified
import scratchattach as sa
import os
from flask import Flask
import subprocess
from threading import Thread
app = Flask(__name__)
def Curl(URL):
# Added a timeout to prevent the app from hanging forever
curl_command = ['curl', '-s', '-X', 'GET', URL]
try:
result = subprocess.run(curl_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10)
if result.returncode == 0:
# Note: .replace() returns a NEW string, it doesn't modify the original
response = result.stdout
response = response.replace("<", "BTTL").replace(">", "BTTR")
return response
except Exception as e:
return f"Curl Error: {str(e)}"
return "No response"
def run_scratch_bot():
sessionid = os.getenv("ID")
useridname = os.getenv("USR")
if not sessionid:
print("CRITICAL: ID (Session ID) environment variable is missing!")
return
try:
# Initialize Scratch session
session = sa.login_by_id(sessionid, username=useridname)
# Check if login actually worked
if session.xtoken is None:
print("FAILED: Session ID is invalid or expired.")
return
cloud = session.connect_cloud("1185047933")
client = cloud.requests()
@client.request
def get_groq_response(user_input):
try:
return Curl(user_input)
except Exception as e:
return f"Error: {str(e)}"
print("Scratch bot is starting...")
client.run() # This runs inside the thread
except Exception as e:
print(f"Scratch connection error: {e}")
# Start the Scratch bot in a background thread so Flask can boot independently
thread = Thread(target=run_scratch_bot)
thread.start()
@app.route('/')
def index():
return "Go to https://scratch.mit.edu/projects/1185047933/ for a live demo."
if __name__ == "__main__":
# Port 7860 is required for Hugging Face
app.run(host="0.0.0.0", port=7860)