euler314 commited on
Commit
8355fb9
·
verified ·
1 Parent(s): 2f21149

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -87
app.py CHANGED
@@ -238,51 +238,58 @@ def install_custom_packages(package_list):
238
  return success, "\n".join(results)
239
 
240
  @st.cache_resource(ttl=3600)
241
- def init_ai_models(model_name=None):
 
242
  try:
243
- # Get the token directly from secrets
244
  token = get_secret("github_token_api")
245
  if not token:
246
- st.error("GitHub token not found in secrets")
247
  return None
248
 
249
- # Use default model or specified model
250
- if not model_name:
251
- model_name = "gpt-4o"
252
 
253
- # Import required modules
 
254
  from azure.ai.inference import ChatCompletionsClient
255
  from azure.ai.inference.models import SystemMessage, UserMessage
256
  from azure.core.credentials import AzureKeyCredential
257
 
258
- # Define endpoint
259
  endpoint = "https://models.inference.ai.azure.com"
260
 
 
 
 
261
  # Create client exactly as in your example
262
  client = ChatCompletionsClient(
263
  endpoint=endpoint,
264
  credential=AzureKeyCredential(token),
265
  )
266
 
267
- # Store client and model info
268
  return {
269
  "client": client,
270
  "model_name": model_name,
271
- "endpoint": endpoint,
272
- "token": token,
273
- "last_loaded": datetime.now().isoformat()
274
  }
 
 
 
 
275
  except Exception as e:
276
- st.error(f"Failed to initialize AI model: {str(e)}")
 
277
  return None
 
278
  def suggest_code_completion(code_snippet, models):
 
279
  if not models or "client" not in models:
280
- st.error("AI models not properly initialized")
281
  return None
282
 
283
  try:
284
- from azure.ai.inference.models import UserMessage
285
-
286
  # Create the prompt
287
  prompt = f"""Write a complete Manim animation scene based on this code or idea:
288
  {code_snippet}
@@ -296,37 +303,41 @@ The code should be a complete, working Manim animation that includes:
296
  Here's the complete Manim code:
297
  """
298
 
299
- # Make API call exactly like your example
300
- response = models["client"].complete(
301
- messages=[
302
- UserMessage(prompt),
303
- ],
304
- max_tokens=1024,
305
- model=models["model_name"]
306
- )
307
-
308
- # Get response content exactly like your example
309
- completed_code = response.choices[0].message.content
310
-
311
- # Clean up the code if it's wrapped in markdown blocks
312
- if "```python" in completed_code:
313
- completed_code = completed_code.split("```python")[1].split("```")[0]
314
- elif "```" in completed_code:
315
- completed_code = completed_code.split("```")[1].split("```")[0]
316
-
317
- # Add Scene class if missing
318
- if "Scene" not in completed_code:
319
- completed_code = f"""from manim import *
 
 
 
320
 
321
  class MyScene(Scene):
322
  def construct(self):
323
  {completed_code}"""
324
-
325
- return completed_code
 
326
  except Exception as e:
327
  st.error(f"Error generating code: {str(e)}")
 
328
  return None
329
-
330
  def check_model_freshness():
331
  """Check if models need to be reloaded based on TTL"""
332
  if 'ai_models' not in st.session_state or st.session_state.ai_models is None:
@@ -1972,12 +1983,71 @@ class MyScene(Scene):
1972
 
1973
  # Check password before allowing access
1974
  if check_password():
1975
- # Model selection - only visible after authentication
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1976
  st.markdown("#### Model Selection")
1977
 
1978
  # Predefined Azure models
1979
  popular_models = [
1980
- "Select a predefined model...",
1981
  "gpt-4o",
1982
  "gpt-4",
1983
  "gpt-35-turbo",
@@ -1985,50 +2055,23 @@ class MyScene(Scene):
1985
  "claude-3-sonnet-20240229",
1986
  ]
1987
 
1988
- custom_model_option = st.radio(
1989
- "Choose model option:",
1990
- ["Use predefined model", "Enter custom model name"]
 
1991
  )
1992
 
1993
- if custom_model_option == "Use predefined model":
1994
- selected_model = st.selectbox(
1995
- "Select a model:",
1996
- options=popular_models
1997
- )
1998
-
1999
- if selected_model != "Select a predefined model...":
2000
- st.session_state.custom_model = selected_model
2001
- else:
2002
- custom_model_name = st.text_input(
2003
- "Enter custom model name:",
2004
- value=st.session_state.custom_model,
2005
- placeholder="e.g., gpt-4o"
2006
- )
2007
-
2008
- if custom_model_name:
2009
- st.session_state.custom_model = custom_model_name
2010
-
2011
- # Display currently selected model
2012
  st.info(f"Currently selected model: {st.session_state.custom_model}")
2013
 
2014
- # Only initialize models if password check passes and we have a model name
2015
- if st.session_state.custom_model:
2016
- model_changed = False
2017
-
2018
- # Check if we need to reinitialize the model (if model changed)
2019
- if (st.session_state.ai_models is not None and
2020
- 'model_name' in st.session_state.ai_models and
2021
- st.session_state.ai_models['model_name'] != st.session_state.custom_model):
2022
- model_changed = True
2023
-
2024
- # Initialize model if needed
2025
- if (st.session_state.ai_models is None or
2026
- not check_model_freshness() or
2027
- model_changed):
2028
- st.session_state.ai_models = init_ai_models(st.session_state.custom_model)
2029
-
2030
- if st.session_state.ai_models:
2031
- # AI code generation
2032
  st.markdown("<div class='card'>", unsafe_allow_html=True)
2033
  st.markdown("#### Generate Animation from Description")
2034
  st.write("Describe the animation you want to create, or provide partial code to complete.")
@@ -2060,16 +2103,67 @@ class MyScene(Scene):
2060
  if st.button("Generate Animation Code", key="gen_ai_code"):
2061
  if code_input:
2062
  with st.spinner("AI is generating your animation code..."):
2063
- response = suggest_code_completion(code_input, st.session_state.ai_models)
2064
- if response:
2065
- st.session_state.generated_code = response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2066
  else:
2067
  st.warning("Please enter a description or prompt first")
2068
 
2069
  st.markdown("</div>", unsafe_allow_html=True)
2070
 
2071
  # AI generated code display and actions
2072
- if st.session_state.generated_code:
2073
  st.markdown("<div class='card'>", unsafe_allow_html=True)
2074
  st.markdown("#### Generated Animation Code")
2075
  st.code(st.session_state.generated_code, language="python")
@@ -2105,7 +2199,7 @@ class MyScene(Scene):
2105
  st.error(f"Failed to generate preview: {status}")
2106
  st.markdown("</div>", unsafe_allow_html=True)
2107
  else:
2108
- st.warning("AI models failed to load. Generation features are unavailable.")
2109
  else:
2110
  st.info("Please enter the correct password to access AI features")
2111
 
 
238
  return success, "\n".join(results)
239
 
240
  @st.cache_resource(ttl=3600)
241
+ def init_ai_models_direct():
242
+ """Direct implementation using the exact pattern from the example code"""
243
  try:
244
+ # Get token from secrets
245
  token = get_secret("github_token_api")
246
  if not token:
247
+ st.error("GitHub token not found in secrets. Please add 'github_token_api' to your HuggingFace Spaces secrets.")
248
  return None
249
 
250
+ # Log what we're doing - for debugging
251
+ logger.info(f"Initializing AI model with token: {token[:5]}...")
 
252
 
253
+ # Use exact imports as in your example
254
+ import os
255
  from azure.ai.inference import ChatCompletionsClient
256
  from azure.ai.inference.models import SystemMessage, UserMessage
257
  from azure.core.credentials import AzureKeyCredential
258
 
259
+ # Use exact endpoint as in your example
260
  endpoint = "https://models.inference.ai.azure.com"
261
 
262
+ # Use default model
263
+ model_name = "gpt-4o"
264
+
265
  # Create client exactly as in your example
266
  client = ChatCompletionsClient(
267
  endpoint=endpoint,
268
  credential=AzureKeyCredential(token),
269
  )
270
 
271
+ # Return the necessary information
272
  return {
273
  "client": client,
274
  "model_name": model_name,
275
+ "endpoint": endpoint
 
 
276
  }
277
+ except ImportError as ie:
278
+ st.error(f"Import error: {str(ie)}. Please make sure azure-ai-inference is installed.")
279
+ logger.error(f"Import error: {str(ie)}")
280
+ return None
281
  except Exception as e:
282
+ st.error(f"Error initializing AI model: {str(e)}")
283
+ logger.error(f"Initialization error: {str(e)}")
284
  return None
285
+
286
  def suggest_code_completion(code_snippet, models):
287
+ """Generate code completion using the AI model"""
288
  if not models or "client" not in models:
289
+ st.error("AI models not properly initialized. Please use the Debug Connection section to test API connectivity.")
290
  return None
291
 
292
  try:
 
 
293
  # Create the prompt
294
  prompt = f"""Write a complete Manim animation scene based on this code or idea:
295
  {code_snippet}
 
303
  Here's the complete Manim code:
304
  """
305
 
306
+ with st.spinner("AI is generating your animation code..."):
307
+ from azure.ai.inference.models import UserMessage
308
+
309
+ # Make an API call exactly like in your example
310
+ response = models["client"].complete(
311
+ messages=[
312
+ UserMessage(prompt),
313
+ ],
314
+ max_tokens=1000,
315
+ model=models["model_name"]
316
+ )
317
+
318
+ # Process the response exactly like in your example
319
+ completed_code = response.choices[0].message.content
320
+
321
+ # Process the code
322
+ if "```python" in completed_code:
323
+ completed_code = completed_code.split("```python")[1].split("```")[0]
324
+ elif "```" in completed_code:
325
+ completed_code = completed_code.split("```")[1].split("```")[0]
326
+
327
+ # Add Scene class if missing
328
+ if "Scene" not in completed_code:
329
+ completed_code = f"""from manim import *
330
 
331
  class MyScene(Scene):
332
  def construct(self):
333
  {completed_code}"""
334
+
335
+ return completed_code
336
+
337
  except Exception as e:
338
  st.error(f"Error generating code: {str(e)}")
339
+ st.code(traceback.format_exc())
340
  return None
 
341
  def check_model_freshness():
342
  """Check if models need to be reloaded based on TTL"""
343
  if 'ai_models' not in st.session_state or st.session_state.ai_models is None:
 
1983
 
1984
  # Check password before allowing access
1985
  if check_password():
1986
+ # Debug section
1987
+ with st.expander("🔧 Debug Connection"):
1988
+ st.markdown("Test the AI model connection directly")
1989
+
1990
+ if st.button("Test API Connection", key="test_api_btn"):
1991
+ with st.spinner("Testing API connection..."):
1992
+ try:
1993
+ # Get token from secrets
1994
+ token = get_secret("github_token_api")
1995
+ if not token:
1996
+ st.error("GitHub token not found in secrets")
1997
+ st.stop()
1998
+
1999
+ # Import required modules
2000
+ import os
2001
+ from azure.ai.inference import ChatCompletionsClient
2002
+ from azure.ai.inference.models import SystemMessage, UserMessage
2003
+ from azure.core.credentials import AzureKeyCredential
2004
+
2005
+ # Define endpoint
2006
+ endpoint = "https://models.inference.ai.azure.com"
2007
+ model_name = "gpt-4o"
2008
+
2009
+ # Create client directly following example
2010
+ client = ChatCompletionsClient(
2011
+ endpoint=endpoint,
2012
+ credential=AzureKeyCredential(token),
2013
+ )
2014
+
2015
+ # Test with a simple prompt
2016
+ response = client.complete(
2017
+ messages=[
2018
+ UserMessage("Hello, this is a connection test."),
2019
+ ],
2020
+ max_tokens=100,
2021
+ model=model_name
2022
+ )
2023
+
2024
+ # Check if response is valid
2025
+ if response and response.choices and len(response.choices) > 0:
2026
+ test_response = response.choices[0].message.content
2027
+ st.success(f"✅ Connection successful! Response: {test_response[:50]}...")
2028
+
2029
+ # Save working connection to session state
2030
+ st.session_state.ai_models = {
2031
+ "client": client,
2032
+ "model_name": model_name,
2033
+ "endpoint": endpoint,
2034
+ "last_loaded": datetime.now().isoformat()
2035
+ }
2036
+ else:
2037
+ st.error("❌ API returned an empty response")
2038
+ except ImportError as ie:
2039
+ st.error(f"Module import error: {str(ie)}")
2040
+ st.info("Try installing required packages: azure-ai-inference and azure-core")
2041
+ except Exception as e:
2042
+ st.error(f"❌ API test failed: {str(e)}")
2043
+ import traceback
2044
+ st.code(traceback.format_exc())
2045
+
2046
+ # Model selection
2047
  st.markdown("#### Model Selection")
2048
 
2049
  # Predefined Azure models
2050
  popular_models = [
 
2051
  "gpt-4o",
2052
  "gpt-4",
2053
  "gpt-35-turbo",
 
2055
  "claude-3-sonnet-20240229",
2056
  ]
2057
 
2058
+ selected_model = st.selectbox(
2059
+ "Select a model:",
2060
+ options=popular_models,
2061
+ index=0
2062
  )
2063
 
2064
+ st.session_state.custom_model = selected_model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2065
  st.info(f"Currently selected model: {st.session_state.custom_model}")
2066
 
2067
+ # Update model if it changed
2068
+ if st.session_state.ai_models and 'model_name' in st.session_state.ai_models:
2069
+ if st.session_state.ai_models['model_name'] != st.session_state.custom_model:
2070
+ st.session_state.ai_models['model_name'] = st.session_state.custom_model
2071
+ st.success(f"Model updated to {st.session_state.custom_model}")
2072
+
2073
+ # AI code generation
2074
+ if st.session_state.ai_models and "client" in st.session_state.ai_models:
 
 
 
 
 
 
 
 
 
 
2075
  st.markdown("<div class='card'>", unsafe_allow_html=True)
2076
  st.markdown("#### Generate Animation from Description")
2077
  st.write("Describe the animation you want to create, or provide partial code to complete.")
 
2103
  if st.button("Generate Animation Code", key="gen_ai_code"):
2104
  if code_input:
2105
  with st.spinner("AI is generating your animation code..."):
2106
+ try:
2107
+ # Direct implementation of code generation
2108
+ client = st.session_state.ai_models["client"]
2109
+ model_name = st.session_state.ai_models["model_name"]
2110
+
2111
+ # Create the prompt
2112
+ prompt = f"""Write a complete Manim animation scene based on this code or idea:
2113
+ {code_input}
2114
+
2115
+ The code should be a complete, working Manim animation that includes:
2116
+ - Proper Scene class definition
2117
+ - Constructor with animations
2118
+ - Proper use of self.play() for animations
2119
+ - Proper wait times between animations
2120
+
2121
+ Here's the complete Manim code:
2122
+ """
2123
+
2124
+ # Make API call directly
2125
+ from azure.ai.inference.models import UserMessage
2126
+ response = client.complete(
2127
+ messages=[
2128
+ UserMessage(prompt),
2129
+ ],
2130
+ max_tokens=1000,
2131
+ model=model_name
2132
+ )
2133
+
2134
+ # Process the response
2135
+ if response and response.choices and len(response.choices) > 0:
2136
+ completed_code = response.choices[0].message.content
2137
+
2138
+ # Extract code from markdown if present
2139
+ if "```python" in completed_code:
2140
+ completed_code = completed_code.split("```python")[1].split("```")[0]
2141
+ elif "```" in completed_code:
2142
+ completed_code = completed_code.split("```")[1].split("```")[0]
2143
+
2144
+ # Add Scene class if missing
2145
+ if "Scene" not in completed_code:
2146
+ completed_code = f"""from manim import *
2147
+
2148
+ class MyScene(Scene):
2149
+ def construct(self):
2150
+ {completed_code}"""
2151
+
2152
+ # Store the generated code
2153
+ st.session_state.generated_code = completed_code
2154
+ else:
2155
+ st.error("Failed to generate code. API returned an empty response.")
2156
+ except Exception as e:
2157
+ st.error(f"Error generating code: {str(e)}")
2158
+ import traceback
2159
+ st.code(traceback.format_exc())
2160
  else:
2161
  st.warning("Please enter a description or prompt first")
2162
 
2163
  st.markdown("</div>", unsafe_allow_html=True)
2164
 
2165
  # AI generated code display and actions
2166
+ if "generated_code" in st.session_state and st.session_state.generated_code:
2167
  st.markdown("<div class='card'>", unsafe_allow_html=True)
2168
  st.markdown("#### Generated Animation Code")
2169
  st.code(st.session_state.generated_code, language="python")
 
2199
  st.error(f"Failed to generate preview: {status}")
2200
  st.markdown("</div>", unsafe_allow_html=True)
2201
  else:
2202
+ st.warning("AI models not initialized. Please use the Debug Connection section to test API connectivity.")
2203
  else:
2204
  st.info("Please enter the correct password to access AI features")
2205