Spaces:
Runtime error
Runtime error
Download app.py from Xjhamx/PasswordManager: direct link, hf CLI and curl.
- Browser
- Download file 5.54 kB
-
https://huggingface.co/spaces/Xjhamx/PasswordManager/resolve/main/app.py
- Command line
-
hf download hf://spaces/Xjhamx/PasswordManager/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Xjhamx/PasswordManager/resolve/main/app.py
5.54 kB
| import re | |
| import json | |
| import os | |
| import gradio as gr | |
| import google.generativeai as genai | |
| # Fallback local | |
| try: | |
| from zxcvbn import zxcvbn | |
| except Exception: | |
| zxcvbn = None # si no está instalado, lo indicamos | |
| genai.configure(api_key=os.environ.get("GOOGLE_API_KEY")) | |
| model_gemini = genai.GenerativeModel(model_name="gemini-2.5-flash") | |
| def parse_json_from_text(text): | |
| """ | |
| Intenta extraer un JSON de la respuesta (puede venir en bloc de código). | |
| Devuelve dict o None. | |
| """ | |
| # Buscar bloque JSON explícito {...} | |
| m = re.search(r'(\{[\s\S]*\})', text) | |
| if not m: | |
| return None | |
| try: | |
| data = json.loads(m.group(1)) | |
| return data | |
| except Exception: | |
| return None | |
| def local_strength_and_advice(password): | |
| """ | |
| Si zxcvbn está disponible, usamos su score para estimar porcentaje. | |
| Si no, aplicamos una heurística simple. | |
| Retorna (percent_int, advice_str). | |
| """ | |
| if zxcvbn: | |
| res = zxcvbn(password) | |
| score = res.get("score", 0) # 0..4 | |
| # Convertimos score(0..4) a porcentaje de facilidad para vulnerar: | |
| # score 4 -> 0% fácil, score 0 -> 100% fácil | |
| percent = int(round((1 - (score / 4)) * 100)) | |
| # Consejos básicos basados en patrones detectados | |
| guesses = res.get("guesses_log10") | |
| suggestions = [] | |
| # zxcvbn suele dar feedback | |
| feedback = res.get("feedback", {}) | |
| if feedback.get("warning"): | |
| suggestions.append(feedback["warning"]) | |
| for s in feedback.get("suggestions", []): | |
| suggestions.append(s) | |
| advice = " ".join(suggestions) if suggestions else ( | |
| "Aumenta la variedad (mayúsculas, números, símbolos) y evita frases completas reconocibles." | |
| ) | |
| return percent, advice | |
| else: | |
| # Heurística simple si no hay zxcvbn | |
| length = len(password) | |
| has_lower = bool(re.search(r'[a-z]', password)) | |
| has_upper = bool(re.search(r'[A-Z]', password)) | |
| has_digit = bool(re.search(r'\d', password)) | |
| has_sym = bool(re.search(r'[^A-Za-z0-9]', password)) | |
| score = 0 | |
| if length >= 12: | |
| score += 2 | |
| elif length >= 8: | |
| score += 1 | |
| if has_upper: score += 1 | |
| if has_digit: score += 1 | |
| if has_sym: score += 1 | |
| # score máximo posible por heurística = 5 | |
| percent = int(round((1 - min(score,5)/5) * 100)) | |
| advice_parts = [] | |
| if not has_upper: advice_parts.append("añade mayúsculas") | |
| if not has_digit: advice_parts.append("añade números") | |
| if not has_sym: advice_parts.append("añade símbolos (ej. !@#)") | |
| if length < 12: advice_parts.append("aumenta la longitud a >=12") | |
| advice = ", ".join(advice_parts) if advice_parts else "Parece razonablemente fuerte; considera usar un passphrase único y un gestor de contraseñas." | |
| return percent, advice | |
| def analizar_contraseña(password): | |
| if not password: | |
| return "Introduce una contraseña." | |
| # Prompt que exige JSON estricto | |
| prompt = f""" | |
| Evalúa la siguiente contraseña: "{password}" | |
| Responde únicamente con un JSON válido (sin texto adicional), con la forma: | |
| {{ | |
| "percent": <entero entre 0 y 100, donde 0 = muy segura, 100 = muy fácil de vulnerar>, | |
| "advice": "<consejos prácticos en español>" | |
| }} | |
| Ejemplo correcto: | |
| {{ | |
| "percent": 72, | |
| "advice": "Explicación concisa con consejos personalizados (sin sugerir gestores de contraseñas)." | |
| }} | |
| """ | |
| try: | |
| response = model_gemini.generate_content([prompt]) | |
| text = response.text if hasattr(response, "text") else str(response) | |
| except Exception as e: | |
| text = f"ERROR_MODEL: {e}" | |
| # Intentar parsear JSON de la respuesta del modelo | |
| parsed = parse_json_from_text(text) | |
| if parsed and isinstance(parsed, dict) and "percent" in parsed: | |
| # normalizamos percent | |
| try: | |
| pct = int(parsed.get("percent", 0)) | |
| pct = max(0, min(100, pct)) | |
| except Exception: | |
| pct = None | |
| advice = parsed.get("advice", "").strip() | |
| if pct is None: | |
| # fallback local | |
| pct, advice_local = local_strength_and_advice(password) | |
| if not advice: advice = advice_local | |
| return f"Porcentaje de facilidad de vulneración: {pct}%\n\nConsejos:\n{advice}" | |
| else: | |
| # Fallback local si el modelo no devolvió JSON válido | |
| pct, advice = local_strength_and_advice(password) | |
| # También incluimos la respuesta del modelo (si existe) para diagnóstico | |
| model_resp_snippet = text.strip() | |
| if len(model_resp_snippet) > 400: | |
| model_resp_snippet = model_resp_snippet[:400] + "..." | |
| return ( | |
| f"(Se usó fallback local porque el modelo no devolvió JSON válido.)\n\n" | |
| f"Porcentaje de facilidad de vulneración: {pct}%\n\n" | |
| f"Consejos:\n{advice}\n\n" | |
| f"Respuesta original del modelo (recortada):\n{model_resp_snippet}" | |
| ) | |
| # Interfaz Gradio | |
| demo = gr.Interface( | |
| fn=analizar_contraseña, | |
| inputs=gr.Textbox(label="Ingrese su contraseña", type="password"), | |
| outputs=gr.Textbox(label="Análisis de seguridad y tasa de descifrado"), | |
| title="🔐 Analizador de Contraseñas con IA (Gemini)", | |
| description="Introduce una contraseña y la IA estimará qué tan fácil sería descifrarla y dará recomendaciones." | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |