File size: 2,020 Bytes
0b8555e a330b1e 0b8555e a330b1e 7500f3a 9fc2a76 cd61a6f 58c8998 9fc2a76 3b2ce0d cd61a6f 3b2ce0d cd61a6f 3b2ce0d 477c07b 0b8555e 58c8998 0b8555e 58c8998 0b8555e 58c8998 0b8555e 58c8998 0b8555e 58c8998 0b8555e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import gradio as gr
# Load the pre-trained GPT2 model and tokenizer
model = GPT2LMHeadModel.from_pretrained("gpt2")
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
# 設置填充標記 ID
tokenizer.pad_token = tokenizer.eos_token
def generate_command(prompt, max_length=100):
full_prompt = f"Generate a Bash command for {prompt}:```bash\n"
inputs = tokenizer.encode(full_prompt, return_tensors="pt")
output = model.generate(
inputs,
max_length=max_length,
num_return_sequences=1,
temperature=0.7,
pad_token_id=tokenizer.pad_token_id
)
generated_text = tokenizer.decode(output[0], skip_special_tokens=False)
# 提取生成的指令
start = generated_text.find("```bash") + len("```bash")
end = generated_text.find("```", start)
if end == -1:
end = len(generated_text)
command = generated_text[start:end].strip()
return command
def predict(input_text):
output = generate_command(input_text)
return output
iface = gr.Interface(
fn=predict,
inputs=gr.Textbox(lines=2, placeholder="Enter your command generation prompt here..."),
outputs="text",
title="Command Generation with GPT2",
description="Generate bash commands based on your input prompt."
)
iface.launch()
```
### 使用示例
1. **生成文件操作指令**:
```python
prompt = "deleting a file"
generated_command = generate_command(prompt)
print(generated_command)
```
可能的輸出:
```
rm filename.txt
```
2. **生成網絡操作指令**:
```python
prompt = "downloading a file from a URL"
generated_command = generate_command(prompt)
print(generated_command)
```
可能的輸出:
```
wget https://example.com/file.txt
```
3. **生成系統管理指令**:
```python
prompt = "checking system memory usage"
generated_command = generate_command(prompt)
print(generated_command) |