Ajedrel commited on
Commit
8b31ca9
·
verified ·
1 Parent(s): d8c83a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -23
app.py CHANGED
@@ -4,27 +4,21 @@ import subprocess
4
  import streamlit as st
5
  from huggingface_hub import InferenceClient
6
 
7
- # Configuración de la página
8
- st.set_page_config(page_title="Python to C++17 Translator", page_icon="⚙️", layout="wide")
9
 
10
- # Inicializar estado del chat
11
  if "messages" not in st.session_state:
12
  st.session_state.messages = []
13
 
14
- # Sidebar para configuración
15
  with st.sidebar:
16
- st.header("Configuración del Modelo")
17
  selected_model = st.selectbox(
18
- "Selecciona el modelo de Hugging Face:",
19
  [
20
- "Qwen/Qwen2.5-Coder-32B-Instruct", # Actualmente el mejor modelo gratuito para código
21
- "Qwen/CodeQwen1.5-7B-Chat",
22
- "meta-llama/CodeLlama-13b-Instruct-hf"
23
  ],
24
  index=0
25
  )
26
 
27
- st.markdown("---")
28
  st.markdown("### Entorno de Ejecución")
29
  st.code("g++ -O3 -std=c++17", language="bash")
30
 
@@ -65,9 +59,7 @@ def compile_and_run_cpp(cpp_code: str) -> str:
65
  compile_cmd = ["g++", "-O3", "-std=c++17", cpp_file, "-o", exe_file]
66
 
67
  try:
68
- # Compilar
69
  comp_process = subprocess.run(compile_cmd, capture_output=True, text=True, check=True)
70
- # Ejecutar
71
  run_process = subprocess.run([exe_file], capture_output=True, text=True, timeout=10)
72
 
73
  output = run_process.stdout
@@ -76,14 +68,13 @@ def compile_and_run_cpp(cpp_code: str) -> str:
76
  return output if output else "Ejecución completada sin salida (stdout vacío)."
77
 
78
  except subprocess.CalledProcessError as e:
79
- return f"⚠️ Error de Compilación:\n{e.stderr}"
80
  except subprocess.TimeoutExpired:
81
- return " Timeout: La ejecución excedió los 10 segundos."
82
 
83
- st.title("🐍 Python ⚙️ C++17 Auto-Translator")
84
- st.markdown("Pega tu código de Python en el chat. El sistema generará la traducción a C++17 y la ejecutará automáticamente.")
85
 
86
- # Renderizar el historial de mensajes
87
  for msg in st.session_state.messages:
88
  with st.chat_message(msg["role"]):
89
  if msg["role"] == "user":
@@ -93,15 +84,14 @@ for msg in st.session_state.messages:
93
  with st.expander("Ver salida de ejecución"):
94
  st.text(msg["content"]["output"])
95
 
96
- # Manejo de nuevo input en el chat
97
- if prompt := st.chat_input("Escribe o pega tu código Python aquí..."):
98
  st.session_state.messages.append({"role": "user", "content": prompt})
99
  with st.chat_message("user"):
100
  st.code(prompt, language="python")
101
 
102
  hf_token = os.getenv("HF_TOKEN")
103
  if not hf_token:
104
- st.error("⚠️ ERROR CRÍTICO: No se encontró el HF_TOKEN. Ve a Settings -> Variables and secrets y configúralo.")
105
  st.stop()
106
 
107
  client = InferenceClient(model=selected_model, token=hf_token)
@@ -112,9 +102,8 @@ if prompt := st.chat_input("Escribe o pega tu código Python aquí..."):
112
  ]
113
 
114
  with st.chat_message("assistant"):
115
- with st.spinner("Conectando con la API y traduciendo a C++17..."):
116
  try:
117
- # Usamos la nueva API de chat (más estable, no requiere Tokenizer local)
118
  response = client.chat_completion(
119
  messages=messages_for_hf,
120
  max_tokens=3000,
@@ -126,7 +115,7 @@ if prompt := st.chat_input("Escribe o pega tu código Python aquí..."):
126
  st.code(clean_cpp, language="cpp")
127
 
128
  st.markdown("---")
129
- st.markdown(" **Ejecutando binario...**")
130
 
131
  with st.spinner("Compilando y ejecutando..."):
132
  execution_output = compile_and_run_cpp(clean_cpp)
 
4
  import streamlit as st
5
  from huggingface_hub import InferenceClient
6
 
7
+ st.set_page_config(page_title="Python to C++17 Translator", layout="wide")
 
8
 
 
9
  if "messages" not in st.session_state:
10
  st.session_state.messages = []
11
 
 
12
  with st.sidebar:
13
+ st.header("Configuracion del Modelo")
14
  selected_model = st.selectbox(
15
+ "Modelo usado:",
16
  [
17
+ "Qwen/Qwen2.5-Coder-32B-Instruct"
 
 
18
  ],
19
  index=0
20
  )
21
 
 
22
  st.markdown("### Entorno de Ejecución")
23
  st.code("g++ -O3 -std=c++17", language="bash")
24
 
 
59
  compile_cmd = ["g++", "-O3", "-std=c++17", cpp_file, "-o", exe_file]
60
 
61
  try:
 
62
  comp_process = subprocess.run(compile_cmd, capture_output=True, text=True, check=True)
 
63
  run_process = subprocess.run([exe_file], capture_output=True, text=True, timeout=10)
64
 
65
  output = run_process.stdout
 
68
  return output if output else "Ejecución completada sin salida (stdout vacío)."
69
 
70
  except subprocess.CalledProcessError as e:
71
+ return f" Error de Compilación:\n{e.stderr}"
72
  except subprocess.TimeoutExpired:
73
+ return " Timeout: La ejecución excedió los 10 segundos."
74
 
75
+ st.title("Python to C++ Auto-Translator")
76
+ st.markdown("Pega tu código de Python en el chat. El sistema generara la traducción a C++ y la ejecutara automaticamente")
77
 
 
78
  for msg in st.session_state.messages:
79
  with st.chat_message(msg["role"]):
80
  if msg["role"] == "user":
 
84
  with st.expander("Ver salida de ejecución"):
85
  st.text(msg["content"]["output"])
86
 
87
+ if prompt := st.chat_input("Escribe o pega tu código Python aqui:"):
 
88
  st.session_state.messages.append({"role": "user", "content": prompt})
89
  with st.chat_message("user"):
90
  st.code(prompt, language="python")
91
 
92
  hf_token = os.getenv("HF_TOKEN")
93
  if not hf_token:
94
+ st.error("ERROR CRÍTICO: No se encontró el HF_TOKEN. Ve a Settings -> Variables and secrets y configuralo.")
95
  st.stop()
96
 
97
  client = InferenceClient(model=selected_model, token=hf_token)
 
102
  ]
103
 
104
  with st.chat_message("assistant"):
105
+ with st.spinner("Conectando con la API y traduciendo a C++"):
106
  try:
 
107
  response = client.chat_completion(
108
  messages=messages_for_hf,
109
  max_tokens=3000,
 
115
  st.code(clean_cpp, language="cpp")
116
 
117
  st.markdown("---")
118
+ st.markdown(" **Ejecutando binario...**")
119
 
120
  with st.spinner("Compilando y ejecutando..."):
121
  execution_output = compile_and_run_cpp(clean_cpp)