# /app.py import os import subprocess from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from pydantic import BaseModel from mistralai.client import MistralClient # --- 1. FastAPI 앱 및 Mistral 클라이언트 초기화 --- app = FastAPI() API_KEY = os.environ.get("MISTRAL_API_KEY") CLIENT = None if API_KEY: try: CLIENT = MistralClient(api_key=API_KEY) print("Mistral API Client initialized successfully.") except Exception as e: print(f"Error initializing Mistral Client: {e}") else: print("FATAL: MISTRAL_API_KEY is not set in Space Secrets.") # --- 2. 백엔드 핵심 기능 함수 --- def generate_c_code(description: str) -> str: """Generates C code based on a natural language description.""" if not CLIENT: return "Error: Mistral API key not configured." prompt = f"You are a C programming expert. Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code within a single ```c code block." messages = [{"role": "user", "content": prompt}] response = CLIENT.chat(model="codestral-latest", messages=messages) code = response.choices[0].message.content if "```c" in code: code = code.split("```c")[1].split("```")[0].strip() elif "```" in code: code = code.split("```")[1].split("```")[0].strip() return code def compile_and_run_c_code(code: str) -> str: """Compiles and runs a given C code snippet and returns its output or any errors.""" try: with open("main.c", "w", encoding='utf-8') as f: f.write(code) compile_proc = subprocess.run( ["gcc", "main.c", "-o", "main.out", "-lm", "-w"], capture_output=True, text=True, timeout=15 ) if compile_proc.returncode != 0: return f"--- COMPILATION FAILED ---\n{compile_proc.stderr}" run_proc = subprocess.run( ["./main.out"], capture_output=True, text=True, timeout=15 ) if run_proc.returncode != 0: return f"--- RUNTIME ERROR ---\n{run_proc.stderr}" output = run_proc.stdout if not output.strip(): return "--- EXECUTION SUCCEEDED ---\n(No output was produced)" return f"--- EXECUTION SUCCEEDED ---\n{output}" except Exception as e: return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}" # --- 3. HTML, CSS, JavaScript 프론트엔드 --- HTML_TEMPLATE = """