OsGo commited on
Commit
07d358b
·
verified ·
1 Parent(s): bce4ba2

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +126 -0
  2. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import datetime
3
+ from pathlib import Path
4
+ import gradio as gr
5
+ import os
6
+ import sys
7
+ import inspect
8
+ from typing import Optional
9
+
10
+
11
+ def make_txt(title: str, content: str) -> str:
12
+ """
13
+ Crea un archivo .txt con un título y contenido y devuelve la ruta al archivo.
14
+ Args:
15
+ title (str): Título del documento.
16
+ content (str): Contenido del documento.
17
+ Returns:
18
+ str: Ruta al archivo creado.
19
+ """
20
+ if title is None:
21
+ title = ""
22
+ # Sanitizar el título para usarlo como nombre de archivo
23
+ safe = re.sub(r'[^A-Za-z0-9 _-]', '', title).strip()
24
+ safe = safe.replace(' ', '_')
25
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
26
+ filename = f"{safe}_{timestamp}.txt" if safe else f"file_{timestamp}.txt"
27
+
28
+ outdir = Path(__file__).parent / "outputs"
29
+ outdir.mkdir(exist_ok=True)
30
+ filepath = outdir / filename
31
+
32
+ header = title if title else "(Sin título)"
33
+ underline = "=" * len(header)
34
+
35
+ with filepath.open("w", encoding="utf-8") as f:
36
+ f.write(header + "\n")
37
+ f.write(underline + "\n\n")
38
+ f.write(content if content else "")
39
+
40
+ return str(filepath)
41
+
42
+
43
+ def build_demo():
44
+ iface = gr.Interface(
45
+ fn=make_txt,
46
+ inputs=[
47
+ gr.Textbox(label="Título", placeholder="Escribe el título aquí"),
48
+ gr.Textbox(label="Contenido", lines=10, placeholder="Escribe el contenido del .txt aquí"),
49
+ ],
50
+ outputs=gr.File(label="Descargar .txt"),
51
+ title="Generador de .txt",
52
+ description="Genera un archivo .txt con un título y contenido."
53
+ )
54
+ return iface
55
+
56
+
57
+ if __name__ == "__main__":
58
+ demo = build_demo()
59
+ # Permitir activar MCP pasando --mcp o configurando la variable de entorno ENABLE_MCP=1
60
+ enable_mcp = "--mcp" in sys.argv or os.getenv("ENABLE_MCP", "").lower() in ("1", "true", "yes")
61
+
62
+ def _get_server_config() -> dict:
63
+ server_name = os.getenv("GRADIO_SERVER_NAME") or os.getenv("SERVER_NAME") or "127.0.0.1"
64
+ try:
65
+ server_port = int(os.getenv("GRADIO_SERVER_PORT") or os.getenv("SERVER_PORT") or "7860")
66
+ except Exception:
67
+ server_port = 7860
68
+ return {"server_name": server_name, "server_port": server_port, "share": False}
69
+
70
+ def launch_demo(demo_obj, enable_mcp_flag: bool = False) -> None:
71
+ base_kwargs = _get_server_config()
72
+ print(f"[info] Launch config: host={base_kwargs['server_name']} port={base_kwargs['server_port']} enable_mcp={enable_mcp_flag}")
73
+
74
+ # If MCP requested, try several strategies to enable it across Gradio versions
75
+ if enable_mcp_flag:
76
+ # First, inspect signature for any known parameter names
77
+ try:
78
+ sig = inspect.signature(demo_obj.launch)
79
+ for param in ("mcp_server", "mcp", "enable_mcp"):
80
+ if param in sig.parameters:
81
+ kwargs = dict(base_kwargs)
82
+ kwargs[param] = True
83
+ print(f"[info] Passing {param}=True based on launch signature.")
84
+ try:
85
+ demo_obj.launch(**kwargs)
86
+ return
87
+ except TypeError as e:
88
+ print(f"[debug] demo.launch(**kwargs) failed with TypeError: {e}")
89
+ except Exception as e:
90
+ print(f"[error] demo.launch raised: {e}")
91
+ except Exception as e:
92
+ print(f"[debug] Could not inspect demo.launch signature: {e}")
93
+
94
+ # Try passing common kwarg names as a fallback
95
+ for param in ("mcp_server", "mcp", "enable_mcp"):
96
+ kwargs = dict(base_kwargs)
97
+ kwargs[param] = True
98
+ try:
99
+ print(f"[info] Trying demo.launch({param}=True) as fallback.")
100
+ demo_obj.launch(**kwargs)
101
+ return
102
+ except TypeError as e:
103
+ print(f"[debug] demo.launch with {param} failed: {e}")
104
+ except Exception as e:
105
+ print(f"[debug] demo.launch with {param} raised: {e}")
106
+
107
+ # If we reach here, we couldn't enable MCP in obvious ways
108
+ print("[warning] No compatible parameter found to enable MCP on this Gradio version.")
109
+ print("[warning] Consider installing 'gradio[mcp]' or updating Gradio. Launching normally.")
110
+
111
+ # Final attempt: launch with base kwargs, with safe fallbacks
112
+ try:
113
+ demo_obj.launch(**base_kwargs)
114
+ except TypeError:
115
+ try:
116
+ # Older versions sometimes don't accept kwargs; call without them
117
+ demo_obj.launch()
118
+ except Exception as e:
119
+ print(f"[error] demo.launch() failed: {e}")
120
+ raise
121
+ except Exception as e:
122
+ print(f"[error] demo.launch(**base_kwargs) raised unexpected error: {e}")
123
+ raise
124
+
125
+ # Launch the demo with the robust launcher
126
+ launch_demo(demo, enable_mcp)
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio[mcp]