Yusuf183-1 commited on
Commit
1c43ccb
·
1 Parent(s): ad1b124

Add secured Gradio app and requirements

Browse files
Files changed (2) hide show
  1. app.py +75 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import logging
4
+
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
6
+ import torch
7
+
8
+ # Configuration
9
+ MODEL_ID = os.environ.get("MODEL_ID", "Salesforce/codegen-350M-mono")
10
+ DEVICE = 0 if torch.cuda.is_available() else -1
11
+
12
+ # Basic logger
13
+ logging.basicConfig(level=logging.INFO, filename='app.log', filemode='a',
14
+ format='%(asctime)s %(levelname)s %(message)s')
15
+
16
+ # Simple blacklist for malicious/illegal code generation requests
17
+ MALICIOUS_KEYWORDS = [
18
+ 'malware', 'ransomware', 'exploit', 'sql injection', 'ddos', 'botnet',
19
+ 'unauthorized access', 'backdoor', 'rootkit', 'phishing', 'password cracking'
20
+ ]
21
+
22
+
23
+ def contains_malicious(prompt: str) -> bool:
24
+ text = prompt.lower()
25
+ return any(k in text for k in MALICIOUS_KEYWORDS)
26
+
27
+
28
+ def load_model():
29
+ try:
30
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
31
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
32
+ gen = pipeline("text-generation", model=model, tokenizer=tokenizer, device=DEVICE)
33
+ logging.info(f"Loaded model {MODEL_ID} on device {DEVICE}")
34
+ return gen
35
+ except Exception as e:
36
+ logging.exception("Model load failed")
37
+ return None
38
+
39
+
40
+ generator = load_model()
41
+
42
+
43
+ def generate_code(prompt: str, max_tokens: int = 128):
44
+ if contains_malicious(prompt):
45
+ logging.warning("Blocked malicious prompt: %s", prompt)
46
+ return "No puedo ayudar con peticiones que impliquen actividades dañinas, ilegales o no autorizadas."
47
+
48
+ if generator is None:
49
+ return "Modelo no cargado correctamente. Comprueba los logs."
50
+
51
+ # Minimal sanitization
52
+ prompt = prompt.strip()
53
+ try:
54
+ outputs = generator(prompt, max_length=max_tokens, do_sample=True, top_p=0.95, temperature=0.2, num_return_sequences=1)
55
+ text = outputs[0]['generated_text']
56
+ logging.info("Generated for prompt: %s", prompt)
57
+ return text
58
+ except Exception as e:
59
+ logging.exception("Generation failed")
60
+ return "Error al generar. Consulta logs."
61
+
62
+
63
+ with gr.Blocks(title="Code Hacker Expert (experimental)") as demo:
64
+ gr.Markdown("# Code Hacker Expert — Experimental\nUsa este espacio solo con prompts legítimos. Se bloquean solicitudes que intenten actividades dañinas o ilegales.")
65
+ with gr.Row():
66
+ prompt = gr.Textbox(lines=6, label="Prompt (describe la función o el fragmento de código que quieres)")
67
+ max_tokens = gr.Slider(minimum=32, maximum=1024, step=32, value=256, label="Máx tokens (salida)")
68
+ btn = gr.Button("Generar código")
69
+ output = gr.Textbox(lines=20, label="Salida")
70
+
71
+ btn.click(fn=generate_code, inputs=[prompt, max_tokens], outputs=output)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ transformers>=4.0.0
2
+ torch
3
+ gradio