chaos4455 commited on
Commit
74d8a54
·
verified ·
1 Parent(s): 21b1ee6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -110
app.py CHANGED
@@ -4,166 +4,166 @@ import json
4
  import re
5
  import datetime
6
 
7
- # Configurações de chave secreta e API do Google Gemini
8
  API_KEY = st.secrets["GOOGLE_API_KEY"]
9
 
10
- # Configuração da página
11
  st.set_page_config(page_title="🤖 Gemini2 PowerShell Command Gen", page_icon="🤖", layout="wide")
12
 
13
- def enviar_mensagem_para_modelo(mensagem, modelo_nome, temperatura, max_tokens):
14
- """Envia uma mensagem para o modelo de IA e retorna a resposta."""
15
  try:
16
- # Configurações do modelo de IA
17
- CONFIGURACAO_GERACAO = {
18
- "temperature": temperatura,
19
  "top_p": 0.8,
20
  "top_k": 40,
21
  "response_mime_type": "text/plain",
22
  "max_output_tokens": max_tokens,
23
  }
24
- MODELO = genai.GenerativeModel(
25
- model_name=modelo_nome,
26
- generation_config=CONFIGURACAO_GERACAO,
27
  )
28
 
29
- resposta = MODELO.start_chat(history=[]).send_message(mensagem)
30
- return resposta.text
31
  except Exception as e:
32
- st.error(f"❌ Erro ao comunicar com a IA: {e}")
33
  return None
34
 
35
- def gerar_comando_powershell(prompt_base, nivel_detalhe, tipo_script, nivel_seguranca, modelo_nome, temperatura, max_tokens, prompt_detail, encoding, add_header, add_error_handling, log_level):
36
- """Gera um comando Powershell com base nas configurações do usuário."""
37
  prompt = f"""
38
- Você é um especialista em Powershell. Sua tarefa é gerar um único comando Powershell com base na seguinte descrição:
39
-
40
- **Objetivo:** Criar o comando Powershell mais completo, detalhado e eficiente possível, considerando todas as variáveis e cenários.
41
-
42
- **Descrição do Comando:** {prompt_base}
43
-
44
- **Nível de Detalhe:** {nivel_detalhe}
45
- **Tipo de Script:** {tipo_script}
46
- **Nível de Segurança:** {nivel_seguranca}
47
- **Nível de Detalhamento do Prompt**:{prompt_detail}
48
-
49
- **Formato da Resposta:**
50
- - Responda em formato Markdown, incluindo um bloco de código Powershell com a formatação original, sem quebrar linhas.
51
- - O bloco de código Powershell deve estar delimitado por ```powershell e ``` .
52
- - Não inclua comentários, explicações ou qualquer outro texto fora do bloco de código.
53
- - O código Powershell deve manter a formatação vertical completa, respeitando indentação e quebras de linha.
54
- - O código deve ser realista, usando exemplos, dados e situações do mundo real.
55
- - Explore diferentes abordagens, técnicas e práticas avançadas.
56
- - Se for gerar um comando com uma cadeia de comandos, não use ponto e virgula no final ou inicio.
57
- - Se precisar use pipe "|" para encadear.
58
- - Não use nenhum tipo de formatação especial no resultado, apenas o código.
59
- - Se a descrição pedir para criar um arquivo, o comando deverá criar o arquivo diretamente no sistema de arquivos e não usar um output em tela para isso.
60
- - Se a descrição pedir para ler um arquivo, o comando deverá ler o arquivo diretamente do sistema de arquivos e não usar um input em tela para isso.
61
- - Use recursos avançados do PowerShell, como pipelines, variáveis, funções e blocos de script, quando necessário.
62
- - O sistema operacional padrão é Windows Server 2016 e a versão do Powershell padrão é a 7, a não ser que o usuário especifique o contrário.
63
- - Certifique-se de que o comando gerado seja seguro e siga as melhores práticas do Powershell.
64
 
65
  **Log Level**:{log_level}
66
- **Tratamento de Erros**:{add_error_handling}
67
 
68
- **Importante:**
69
- - Gere apenas um comando por vez.
70
- - Crie o código o mais longo, completo e detalhado possível.
71
- - Considere todos os detalhes do pedido, expandindo a resposta e melhorando o comando.
72
- - Use as informações contextuais (como versão do PowerShell e sistema operacional) para gerar o comando.
73
- - Se possível, use um raciocínio incremental para adicionar melhorias, expansões e considerações ao seu código
74
- - Use o historico das conversas para que a resposta seja incremental
75
 
76
  """
77
- resposta = enviar_mensagem_para_modelo(prompt, modelo_nome, temperatura, max_tokens)
78
- return resposta
79
 
80
- def parsear_e_salvar_ps1(codigo_ia, titulo_curto, encoding, add_header):
81
- """Parseia o markdown e salva o código Powershell como .ps1."""
82
- match = re.search(r'```powershell\s*(.*?)\s*```', codigo_ia, re.DOTALL | re.IGNORECASE)
83
  if match:
84
- codigo_ps1 = match.group(1).strip()
85
  else:
86
- codigo_ps1 = codigo_ia.strip()
87
 
88
- nome_arquivo = f"comando_{titulo_curto}.ps1"
89
 
90
  if add_header:
91
- data_atual = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
92
  header = f"""
93
  #===============================================================================
94
- # Script Gerado pelo Google Gemini 2 PowerShell Command Gen
95
- # Data: {data_atual}
96
- # Autor: Elias Andrade
97
  #===============================================================================
98
  """
99
- codigo_ps1 = header + codigo_ps1
100
 
101
- with open(nome_arquivo, "w", encoding=encoding) as f:
102
- f.write(codigo_ps1)
103
- return nome_arquivo, codigo_ps1
104
 
105
  def main():
106
  st.title("🤖 Gemini2 PowerShell Command Gen by [Elias Andrade](https://github.com/chaos4455)")
107
- st.markdown("Crie comandos PowerShell de forma fácil e rápida! 🚀")
108
  st.markdown("---")
109
 
110
- # Layout em colunas (barra lateral e principal)
111
  col1, col2 = st.columns([1, 3])
112
 
113
  with col1:
114
- st.header("⚙️ Configurações")
115
 
116
- with st.expander("✨ Configurações da IA"):
117
- modelo_nome = st.selectbox("🤖 Modelo da IA", ["gemini-2.0-flash-exp", "gemini-1.5-flash-exp"], index=0, help="Escolha o modelo da IA.")
118
- temperatura = st.slider("🌡️ Temperatura", min_value=0.1, max_value=1.0, value=0.7, step=0.1, help="Ajuste a criatividade da IA.")
119
- max_tokens = st.number_input("📏 Max Tokens", min_value=128, max_value=8192, value=8192, step=128, help="Ajuste o tamanho máximo da resposta.")
120
 
121
- with st.expander("📝 Configurações do Prompt"):
122
- prompt_presets = st.selectbox("🎯 Prompts Predefinidos", ["Nenhum", "Listar arquivos", "Gerenciar processos", "Gerenciar serviços"], index=0, help="Escolha um prompt predefinido.")
123
- prompt_detail = st.selectbox("🧐 Detalhe do Prompt", ["Mais descritivo", "Padrão", "Conciso"], index=1, help="Define o nível de detalhe do prompt")
124
-
125
- with st.expander("🛠️ Configurações do PowerShell"):
126
- powershell_version = st.selectbox("🎛️ Versão do PowerShell", ["7", "5.1"], index=0, help="Escolha a versão do PowerShell")
127
- sistema_operacional = st.selectbox(
128
- "💻 Sistema Operacional",
129
  [
130
  "Windows Server 2022", "Windows Server 2019", "Windows Server 2016",
131
  "Windows Server 2012 R2", "Windows Server 2012", "Windows Server 2008 R2",
132
- "Windows Server 2008", "Windows 11", "Windows 10","Windows 8.1", "Windows 8","Windows 7", "Outro"
133
  ],
134
- index=2, help="Escolha o Sistema Operacional de destino."
135
  )
136
- encoding = st.selectbox("🔤 Encoding", ["utf-8", "ansi"], index=0, help="Escolha o encoding do arquivo .ps1")
137
- add_header = st.checkbox("📜 Adicionar Cabeçalho", value=True, help="Adicionar um cabeçalho com informações no arquivo .ps1")
138
- add_error_handling = st.checkbox("🛡️ Tratamento de Erros", value=True, help="Adicionar tratamento de erros padrão no script")
139
- log_level = st.selectbox("🗂️ Nível de Logging", ["Detalhado", "Padrão", "Mínimo"], index=1, help="Define o nível de detalhe de logs.")
140
 
141
- nivel_detalhe = st.selectbox(" Nível de Detalhe", ["Mais detalhado", "Padrão", "Mais conciso"], index=1)
142
- tipo_script = st.selectbox(" Tipo de Script", ["Mais automático", "Mais interativo"], index=0)
143
- nivel_seguranca = st.radio(" Nível de Segurança", ["Alto", "Médio", "Baixo"], index=1)
144
 
145
  with col2:
146
- # Prompt base do usuário
147
- prompt_base = st.text_input("Descreva o Comando PowerShell:", placeholder="Ex: Liste todos os processos em execução", key="prompt_base")
148
 
149
- if prompt_presets != "Nenhum":
150
  if prompt_base:
151
  prompt_base = f"{prompt_presets} , {prompt_base}"
152
  else:
153
  prompt_base = prompt_presets;
154
- if st.button("✨ Gerar Comando PowerShell"):
155
  if not prompt_base:
156
- st.error("⚠️ Por favor, insira uma descrição do comando.")
157
  return
158
 
159
- with st.spinner("⏳ Gerando comando..."):
160
- codigo_ia = gerar_comando_powershell(
161
  prompt_base,
162
- nivel_detalhe,
163
- tipo_script,
164
- nivel_seguranca,
165
- modelo_nome,
166
- temperatura,
167
  max_tokens,
168
  prompt_detail,
169
  encoding,
@@ -172,21 +172,21 @@ def main():
172
  log_level
173
  )
174
 
175
- if codigo_ia:
176
- st.markdown("### ✅ Comando Gerado:")
177
- st.code(codigo_ia, language="powershell")
178
 
179
- titulo_curto = prompt_base[:30].strip().replace(" ", "_").lower()
180
- nome_arquivo_ps1, codigo_ps1 = parsear_e_salvar_ps1(codigo_ia, titulo_curto, encoding, add_header)
181
 
182
  st.download_button(
183
- label="⬇️ Baixar Comando (.ps1)",
184
- data=codigo_ps1,
185
- file_name=nome_arquivo_ps1,
186
  mime="application/powershell",
187
  )
188
  else:
189
- st.error("❌ Erro ao gerar o comando. Verifique a conexão com a IA e tente novamente.")
190
 
191
  if __name__ == "__main__":
192
  main()
 
4
  import re
5
  import datetime
6
 
7
+ # Secret key and Google Gemini API configuration
8
  API_KEY = st.secrets["GOOGLE_API_KEY"]
9
 
10
+ # Page configuration
11
  st.set_page_config(page_title="🤖 Gemini2 PowerShell Command Gen", page_icon="🤖", layout="wide")
12
 
13
+ def send_message_to_model(message, model_name, temperature, max_tokens):
14
+ """Sends a message to the AI model and returns the response."""
15
  try:
16
+ # AI model configurations
17
+ GENERATION_CONFIG = {
18
+ "temperature": temperature,
19
  "top_p": 0.8,
20
  "top_k": 40,
21
  "response_mime_type": "text/plain",
22
  "max_output_tokens": max_tokens,
23
  }
24
+ MODEL = genai.GenerativeModel(
25
+ model_name=model_name,
26
+ generation_config=GENERATION_CONFIG,
27
  )
28
 
29
+ response = MODEL.start_chat(history=[]).send_message(message)
30
+ return response.text
31
  except Exception as e:
32
+ st.error(f"❌ Error communicating with the AI: {e}")
33
  return None
34
 
35
+ def generate_powershell_command(prompt_base, detail_level, script_type, security_level, model_name, temperature, max_tokens, prompt_detail, encoding, add_header, add_error_handling, log_level):
36
+ """Generates a PowerShell command based on user settings."""
37
  prompt = f"""
38
+ You are a Powershell expert. Your task is to generate a single Powershell command based on the following description:
39
+
40
+ **Goal:** Create the most complete, detailed, and efficient Powershell command possible, considering all variables and scenarios.
41
+
42
+ **Command Description:** {prompt_base}
43
+
44
+ **Detail Level:** {detail_level}
45
+ **Script Type:** {script_type}
46
+ **Security Level:** {security_level}
47
+ **Prompt Detail Level**:{prompt_detail}
48
+
49
+ **Response Format:**
50
+ - Respond in Markdown format, including a Powershell code block with its original formatting, without line breaks.
51
+ - The Powershell code block must be delimited by ```powershell and ```.
52
+ - Do not include comments, explanations, or any other text outside the code block.
53
+ - The Powershell code must maintain its full vertical formatting, respecting indentation and line breaks.
54
+ - The code must be realistic, using real-world examples, data, and situations.
55
+ - Explore different approaches, techniques, and advanced practices.
56
+ - If generating a command with a chain of commands, do not use semicolons at the end or beginning.
57
+ - If necessary, use the pipe "|" to chain commands.
58
+ - Do not use any special formatting in the result, only the code.
59
+ - If the description asks to create a file, the command should create the file directly in the file system and not use a screen output for this.
60
+ - If the description asks to read a file, the command should read the file directly from the file system and not use a screen input for this.
61
+ - Use advanced PowerShell resources, such as pipelines, variables, functions, and script blocks, when necessary.
62
+ - The default operating system is Windows Server 2016, and the default Powershell version is 7, unless the user specifies otherwise.
63
+ - Make sure that the generated command is secure and follows the best Powershell practices.
64
 
65
  **Log Level**:{log_level}
66
+ **Error Handling**:{add_error_handling}
67
 
68
+ **Important:**
69
+ - Generate only one command at a time.
70
+ - Create the longest, most complete, and detailed code possible.
71
+ - Consider all the details of the request, expanding the response and improving the command.
72
+ - Use contextual information (such as PowerShell version and operating system) to generate the command.
73
+ - If possible, use incremental reasoning to add improvements, expansions, and considerations to your code.
74
+ - Use the history of the conversations so that the response is incremental.
75
 
76
  """
77
+ response = send_message_to_model(prompt, model_name, temperature, max_tokens)
78
+ return response
79
 
80
+ def parse_and_save_ps1(ai_code, short_title, encoding, add_header):
81
+ """Parses the markdown and saves the Powershell code as .ps1."""
82
+ match = re.search(r'```powershell\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
83
  if match:
84
+ ps1_code = match.group(1).strip()
85
  else:
86
+ ps1_code = ai_code.strip()
87
 
88
+ file_name = f"command_{short_title}.ps1"
89
 
90
  if add_header:
91
+ current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
92
  header = f"""
93
  #===============================================================================
94
+ # Script Generated by Google Gemini 2 PowerShell Command Gen
95
+ # Date: {current_date}
96
+ # Author: Elias Andrade AKA Chaos4455
97
  #===============================================================================
98
  """
99
+ ps1_code = header + ps1_code
100
 
101
+ with open(file_name, "w", encoding=encoding) as f:
102
+ f.write(ps1_code)
103
+ return file_name, ps1_code
104
 
105
  def main():
106
  st.title("🤖 Gemini2 PowerShell Command Gen by [Elias Andrade](https://github.com/chaos4455)")
107
+ st.markdown("Create PowerShell commands easily and quickly! 🚀")
108
  st.markdown("---")
109
 
110
+ # Layout in columns (sidebar and main area)
111
  col1, col2 = st.columns([1, 3])
112
 
113
  with col1:
114
+ st.header("⚙️ Settings")
115
 
116
+ with st.expander("✨ AI Settings"):
117
+ model_name = st.selectbox("🤖 AI Model", ["gemini-2.0-flash-exp", "gemini-1.5-flash-exp"], index=0, help="Choose the AI model.")
118
+ temperature = st.slider("🌡️ Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.1, help="Adjust the AI's creativity.")
119
+ max_tokens = st.number_input("📏 Max Tokens", min_value=128, max_value=8192, value=8192, step=128, help="Adjust the maximum size of the response.")
120
 
121
+ with st.expander("📝 Prompt Settings"):
122
+ prompt_presets = st.selectbox("🎯 Predefined Prompts", ["None", "List files", "Manage processes", "Manage services"], index=0, help="Choose a predefined prompt.")
123
+ prompt_detail = st.selectbox("🧐 Prompt Detail", ["More descriptive", "Default", "Concise"], index=1, help="Defines the level of detail of the prompt")
124
+
125
+ with st.expander("🛠️ PowerShell Settings"):
126
+ powershell_version = st.selectbox("🎛️ PowerShell Version", ["7", "5.1"], index=0, help="Choose the PowerShell version.")
127
+ operating_system = st.selectbox(
128
+ "💻 Operating System",
129
  [
130
  "Windows Server 2022", "Windows Server 2019", "Windows Server 2016",
131
  "Windows Server 2012 R2", "Windows Server 2012", "Windows Server 2008 R2",
132
+ "Windows Server 2008", "Windows 11", "Windows 10", "Windows 8.1", "Windows 8", "Windows 7", "Other"
133
  ],
134
+ index=2, help="Choose the target operating system."
135
  )
136
+ encoding = st.selectbox("🔤 Encoding", ["utf-8", "ansi"], index=0, help="Choose the encoding of the .ps1 file.")
137
+ add_header = st.checkbox("📜 Add Header", value=True, help="Add a header with information in the .ps1 file.")
138
+ add_error_handling = st.checkbox("🛡️ Error Handling", value=True, help="Add standard error handling to the script.")
139
+ log_level = st.selectbox("🗂️ Logging Level", ["Detailed", "Default", "Minimum"], index=1, help="Defines the detail level of logs.")
140
 
141
+ detail_level = st.selectbox("Detail Level", ["More detailed", "Default", "More concise"], index=1)
142
+ script_type = st.selectbox("Script Type", ["More automatic", "More interactive"], index=0)
143
+ security_level = st.radio("Security Level", ["High", "Medium", "Low"], index=1)
144
 
145
  with col2:
146
+ # User's base prompt
147
+ prompt_base = st.text_input("Describe the PowerShell Command:", placeholder="Ex: List all running processes", key="prompt_base")
148
 
149
+ if prompt_presets != "None":
150
  if prompt_base:
151
  prompt_base = f"{prompt_presets} , {prompt_base}"
152
  else:
153
  prompt_base = prompt_presets;
154
+ if st.button("✨ Generate PowerShell Command"):
155
  if not prompt_base:
156
+ st.error("⚠️ Please enter a command description.")
157
  return
158
 
159
+ with st.spinner("⏳ Generating command..."):
160
+ ai_code = generate_powershell_command(
161
  prompt_base,
162
+ detail_level,
163
+ script_type,
164
+ security_level,
165
+ model_name,
166
+ temperature,
167
  max_tokens,
168
  prompt_detail,
169
  encoding,
 
172
  log_level
173
  )
174
 
175
+ if ai_code:
176
+ st.markdown("### ✅ Generated Command:")
177
+ st.code(ai_code, language="powershell")
178
 
179
+ short_title = prompt_base[:30].strip().replace(" ", "_").lower()
180
+ file_name_ps1, ps1_code = parse_and_save_ps1(ai_code, short_title, encoding, add_header)
181
 
182
  st.download_button(
183
+ label="⬇️ Download Command (.ps1)",
184
+ data=ps1_code,
185
+ file_name=file_name_ps1,
186
  mime="application/powershell",
187
  )
188
  else:
189
+ st.error("❌ Error generating the command. Check the connection with the AI and try again.")
190
 
191
  if __name__ == "__main__":
192
  main()