Spaces:
Running
Running
Update app.py
Browse files348 unmodified lines34935035135235335435535613 unmodified lines3703713723733743753763773783793803813823833843851762 unmodified lines214821492150215121522153215421 unmodified lines2176217721782179218021812182135 unmodified lines23182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236226 unmodified lines238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224233 unmodified lines2427242824292430243124322433243424352436348 unmodified lines# Get the current model name and base URLmodel_name = models["model_name"]# Convert message to the appropriate format based on model categoryconfig = MODEL_CONFIGS.get(model_name, MODEL_CONFIGS["default"])category = config.get("category", "Other")if category == "OpenAI":13 unmodified lineselse:client = models["openai_client"]# For OpenAI models, we need role-based messagesmessages = [{"role": "system", "content": "You are an expert in Manim animations."},{"role": "user", "content": prompt}]# Create paramsparams = {"messages": messages,"model": model_name}# Add token parameter1762 unmodified lines# Get model detailsmodel_name = st.session_state.custom_modelconfig = MODEL_CONFIGS.get(model_name, MODEL_CONFIGS["default"])category = config.get("category", "Other")if category == "OpenAI":21 unmodified lines# Prepare parameters based on model configurationparams = {"messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello, this is a connection test."}],"model": full_model_name135 unmodified lines# Add a refresh button to update model connectionif st.button("🔄 Refresh Model Connection", key="refresh_model_connection"):if st.session_state.ai_models and 'client' in st.session_state.ai_models:try:# Test connection with minimal promptfrom azure.ai.inference.models import UserMessagemodel_name = st.session_state.custom_model# Prepare parametersmessages = [UserMessage("Hello")]api_params, config = prepare_api_params(messages, model_name)# Check if we need a new client with specific API versionif config["api_version"] and config["api_version"] != st.session_state.ai_models.get("api_version"):# Create version-specific client if neededtoken = get_secret("github_token_api")from azure.ai.inference import ChatCompletionsClientfrom azure.core.credentials import AzureKeyCredentialclient = ChatCompletionsClient(endpoint=st.session_state.ai_models["endpoint"],credential=AzureKeyCredential(token),api_version=config["api_version"])response = client.complete(**api_params)# Update session state with the new clientst.session_state.ai_models["client"] = clientst.session_state.ai_models["api_version"] = config["api_version"]else:response = st.session_state.ai_models["client"].complete(**api_params)st.success(f"✅ Connection to {model_name} successful!")st.session_state.ai_models["model_name"] = model_nameexcept Exception as e:st.error(f"❌ Connection error: {str(e)}")st.info("Please try the Debug Connection section to re-initialize the API connection.")# AI code generationif st.session_state.ai_models and "client" in st.session_state.ai_models:st.markdown("<div class='card'>", unsafe_allow_html=True)st.markdown("#### Generate Animation from Description")st.write("Describe the animation you want to create, or provide partial code to complete.")26 unmodified linesif code_input:with st.spinner("AI is generating your animation code..."):try:# Get the client and model nameclient = st.session_state.ai_models["client"]model_name = st.session_state.ai_models["model_name"]# Create the promptprompt = f"""Write a complete Manim animation scene based on this code or idea:{code_input}The code should be a complete, working Manim animation that includes:- Proper Scene class definition- Constructor with animations- Proper use of self.play() for animations- Proper wait times between animationsHere's the complete Manim code:"""# Prepare API parametersfrom azure.ai.inference.models import UserMessagemessages = [UserMessage(prompt)]api_params, config = prepare_api_params(messages, model_name)# Make the API call with proper parametersresponse = client.complete(**api_params)# Process the responseif response and response.choices and len(response.choices) > 0:completed_code = response.choices[0].message.content# Extract code from markdown if presentif "```python" in completed_code:completed_code = completed_code.split("```python")[1].split("```")[0]3 unmodified lines# Add Scene class if missingif "Scene" not in completed_code:completed_code = f"""from manim import *class MyScene(Scene):def construct(self):{completed_code}"""# Store the generated codest.session_state.generated_code = completed_code348 unmodified lines34935035135235335435535635735835913 unmodified lines3733743753763773783793803813823833843853863873883893903913923933941762 unmodified lines2157215821592160216121622163216421 unmodified lines2186218721882189219021912192135 unmodified lines232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241526 unmodified lines2442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025013 unmodified lines2505250625072508250925102511251225132514348 unmodified lines# Get the current model name and base URLmodel_name = models["model_name"]# Handle model name - extract base name if it has a prefixbase_model_name = model_name.split('/')[-1] if '/' in model_name else model_name# Convert message to the appropriate format based on model categoryconfig = MODEL_CONFIGS.get(base_model_name, MODEL_CONFIGS["default"])category = config.get("category", "Other")if category == "OpenAI":13 unmodified lineselse:client = models["openai_client"]# Add openai/ prefix if not presentif "/" not in model_name:full_model_name = f"openai/{model_name}"else:full_model_name = model_name# For OpenAI models, use developer role instead of systemmessages = [{"role": "developer", "content": "You are an expert in Manim animations."},{"role": "user", "content": prompt}]# Create paramsparams = {"messages": messages,"model": full_model_name}# Add token parameter1762 unmodified lines# Get model detailsmodel_name = st.session_state.custom_modelbase_model_name = model_name.split('/')[-1] if '/' in model_name else model_nameconfig = MODEL_CONFIGS.get(base_model_name, MODEL_CONFIGS["default"])category = config.get("category", "Other")if category == "OpenAI":21 unmodified lines# Prepare parameters based on model configurationparams = {"messages": [{"role": "developer", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello, this is a connection test."}],"model": full_model_name135 unmodified lines# Add a refresh button to update model connectionif st.button("🔄 Refresh Model Connection", key="refresh_model_connection"):if st.session_state.ai_models:try:# Get model detailsmodel_name = st.session_state.custom_modelbase_model_name = model_name.split('/')[-1] if '/' in model_name else model_nameconfig = MODEL_CONFIGS.get(base_model_name, MODEL_CONFIGS["default"])category = config.get("category", "Other")if category == "OpenAI":# Get tokentoken = get_secret("github_token_api")# Create new OpenAI clientfrom openai import OpenAIclient = OpenAI(base_url="https://models.github.ai/inference",api_key=token)# Add openai/ prefix if not presentif "/" not in model_name:full_model_name = f"openai/{model_name}"else:full_model_name = model_name# Test with minimal promptresponse = client.chat.completions.create(messages=[{"role": "developer", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello, this is a test."}],model=full_model_name,**{config["param_name"]: config[config["param_name"]]})# Update session statest.session_state.ai_models = {"openai_client": client,"model_name": full_model_name,"endpoint": "https://models.github.ai/inference","last_loaded": datetime.now().isoformat(),"category": category}st.success(f"✅ Connection to {full_model_name} refreshed successfully!")else:# Test connection with minimal prompt for Azure modelsfrom azure.ai.inference.models import UserMessage# Prepare parametersmessages = [UserMessage("Hello")]api_params, config = prepare_api_params(messages, model_name)# Check if we need a new client with specific API versionif config["api_version"] and config["api_version"] != st.session_state.ai_models.get("api_version"):# Create version-specific client if neededtoken = get_secret("github_token_api")from azure.ai.inference import ChatCompletionsClientfrom azure.core.credentials import AzureKeyCredentialclient = ChatCompletionsClient(endpoint=st.session_state.ai_models["endpoint"],credential=AzureKeyCredential(token),api_version=config["api_version"])response = client.complete(**api_params)# Update session state with the new clientst.session_state.ai_models["client"] = clientst.session_state.ai_models["api_version"] = config["api_version"]else:response = st.session_state.ai_models["client"].complete(**api_params)st.success(f"✅ Connection to {model_name} successful!")st.session_state.ai_models["model_name"] = model_nameexcept Exception as e:st.error(f"❌ Connection error: {str(e)}")st.info("Please try the Debug Connection section to re-initialize the API connection.")# AI code generationif st.session_state.ai_models:st.markdown("<div class='card'>", unsafe_allow_html=True)st.markdown("#### Generate Animation from Description")st.write("Describe the animation you want to create, or provide partial code to complete.")26 unmodified linesif code_input:with st.spinner("AI is generating your animation code..."):try:# Get model detailsmodel_name = st.session_state.ai_models["model_name"]base_model_name = model_name.split('/')[-1] if '/' in model_name else model_nameconfig = MODEL_CONFIGS.get(base_model_name, MODEL_CONFIGS["default"])category = config.get("category", "Other")# Create the promptprompt = f"""Write a complete Manim animation scene based on this code or idea:{code_input}The code should be a complete, working Manim animation that includes:- Proper Scene class definition- Constructor with animations- Proper use of self.play() for animations- Proper wait times between animationsHere's the complete Manim code:"""if category == "OpenAI":# Use OpenAI clientclient = st.session_state.ai_models["openai_client"]# Use developer role instead of systemmessages = [{"role": "developer", "content": "You are an expert in Manim animations."},{"role": "user", "content": prompt}]# Create paramsparams = {"messages": messages,"model": model_name,config["param_name"]: config[config["param_name"]]}# Call APIresponse = client.chat.completions.create(**params)completed_code = response.choices[0].message.contentelse:# Use Azure client for non-OpenAI modelsfrom azure.ai.inference.models import UserMessageclient = st.session_state.ai_models["client"]# Convert message format for Azuremessages = [UserMessage(prompt)]api_params, _ = prepare_api_params(messages, model_name)# Make API call with Azure clientresponse = client.complete(**api_params)completed_code = response.choices[0].message.content# Process the responseif completed_code:# Extract code from markdown if presentif "```python" in completed_code:completed_code = completed_code.split("```python")[1].split("```")[0]3 unmodified lines# Add Scene class if missingif "Scene" not in completed_code:completed_code = f"""from manim import *class MyScene(Scene):def construct(self):{completed_code}"""# Store the generated codest.session_state.generated_code = completed_code
app.py+135-57