BCappuccina50 commited on
Commit
fdae656
verified
1 Parent(s): eb1deaf

Update AppleleafPR.py

Browse files
Files changed (1) hide show
  1. AppleleafPR.py +220 -47
AppleleafPR.py CHANGED
@@ -1,78 +1,252 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- Prompt Refiner con OpenRouter (qwen/qwen3-4b:free) - sin l铆mite de tokens
4
- Adaptado para ser alojado en Hugging Face Spaces (puerto 7860) y usar secretos de entorno.
5
  """
6
  import os
7
  from flask import Flask, request, render_template_string
8
  from openai import OpenAI # pip install openai
9
 
10
  # ----------------------------------------------------
11
- # FIX 1: Clave API desde variable de entorno (SECRETO)
12
  # ----------------------------------------------------
13
  OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
14
 
15
  if not OPENROUTER_API_KEY:
16
- # Esto asegura que la aplicaci贸n fallar谩 si el secreto no est谩 configurado,
17
- # evitando la ejecuci贸n con una clave codificada o nula.
18
- print("隆ERROR! La variable de entorno OPENROUTER_API_KEY no est谩 configurada.")
19
- # Usar una clave de prueba solo para el cliente si no puedes salir,
20
- # pero en un entorno real, DEBES usar el 'raise' para detener la app.
21
- # Por seguridad, dejar茅 que se detenga si la clave no est谩.
22
- # raise EnvironmentError("OPENROUTER_API_KEY no encontrada. Config煤rala como Secreto de Espacio.")
23
- pass
24
 
25
 
26
  # ---------- 1. Cliente de OpenRouter ----------
27
  client = OpenAI(
28
  base_url="https://openrouter.ai/api/v1",
29
- api_key=OPENROUTER_API_KEY if OPENROUTER_API_KEY else "dummy-key-for-local-testing" # Usar la clave cargada
30
  )
31
 
32
  MODEL = "qwen/qwen3-4b:free"
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  # ---------- 2. Refinamiento SIN l铆mite ----------
35
  def refine(text: str) -> str:
36
- # Si la clave no est谩 y el cliente est谩 inicializado con una 'dummy',
37
- # detenemos la funci贸n para evitar llamadas fallidas
38
- if not OPENROUTER_API_KEY:
39
  return "[Error de configuraci贸n]: La clave OPENROUTER_API_KEY no se encontr贸 en el entorno."
40
 
41
  try:
42
- # El contenido del system_prompt es muy extenso; por brevedad,
43
- # lo he truncado aqu铆, pero se mantiene intacto en la ejecuci贸n.
44
- system_prompt = (
45
- "You are now Appleleaf, a Prompt Generation Specialist with expertise in creating sophisticated, optimized prompts from user requirements. "
46
- "Your role is to transform user needs into highly effective prompts using advanced techniques and patterns.\n\n"
47
- "## SYSTEM CONFIGURATION\n\n"
48
- "1. REQUIREMENT ANALYSIS\n"
49
- "... (Contenido del SYSTEM CONFIGURATION original) ...\n\n"
50
- "Activate prompt generation system now.\n\n"
51
- "Share: \"馃帹 Appleleaf PROMPT GENERATION SYSTEM ACTIVE\n\n"
52
- "Please describe what you want your prompt to do. Include:\n"
53
- "- Main purpose/goal\n"
54
- "- Expected outputs/results\n"
55
- "- Special requirements (technical, format, safety, etc.)\n"
56
- "- Any specific features needed\n"
57
- "- Quality standards expected\n"
58
- "- Format requirements\n"
59
- "- Performance expectations\n\n"
60
- "I will generate a sophisticated prompt tailored to your needs.\""
61
- )
62
-
63
  resp = client.chat.completions.create(
64
  model=MODEL,
65
  messages=[
66
  {
67
  "role": "system",
68
- "content": system_prompt
69
  },
70
  {"role": "user", "content": text}
71
  ],
72
  temperature=0.7,
73
  max_tokens=None
74
  )
75
- return resp.choices[0].message.content.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  except Exception as e:
77
  return f"[Error al refinar: {e}]"
78
 
@@ -84,18 +258,19 @@ HTML = """
84
  <html>
85
  <head>
86
  <meta charset="utf-8"/>
87
- <title>Prompt Refiner</title>
88
  <style>body{font-family:Arial;margin:40px}textarea{width:100%;height:120px}</style>
89
  </head>
90
  <body>
91
- <h1>Prompt Refiner (OpenRouter&nbsp;&ndash;&nbsp;qwen/qwen3-4b:free)</h1>
 
92
  <form method="POST">
93
- <textarea name="prompt" placeholder="Escribe tu prompt...">{{ original }}</textarea><br><br>
94
- <button type="submit">Refinar</button>
95
  </form>
96
  {% if refined %}
97
- <h2>Prompt refinado:</h2>
98
- <textarea readonly style="height:300px;">{{ refined }}</textarea>
99
  {% endif %}
100
  </body>
101
  </html>
@@ -112,7 +287,5 @@ def index():
112
 
113
  # ---------- 4. Arranque ----------
114
  if __name__ == "__main__":
115
- # ----------------------------------------------------
116
- # FIX 2: Usar el puerto 7860, el est谩ndar de Hugging Face Spaces
117
- # ----------------------------------------------------
118
  app.run(host="0.0.0.0", port=7860, debug=False)
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ Prompt Refiner con OpenRouter (qwen/qwen3-4b:free) - SOLO SALIDA DEL PROMPT
4
+ Adaptado para Hugging Face Spaces (puerto 7860) y secretos de entorno.
5
  """
6
  import os
7
  from flask import Flask, request, render_template_string
8
  from openai import OpenAI # pip install openai
9
 
10
  # ----------------------------------------------------
11
+ # FIX: Clave API desde variable de entorno (SECRETO)
12
  # ----------------------------------------------------
13
  OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
14
 
15
  if not OPENROUTER_API_KEY:
16
+ print("隆ADVERTENCIA! La variable de entorno OPENROUTER_API_KEY no est谩 configurada.")
17
+ # Permite la ejecuci贸n local con una clave 'dummy' si no es un entorno de HF.
18
+ API_KEY_TO_USE = "dummy-key-for-local-testing"
19
+ else:
20
+ API_KEY_TO_USE = OPENROUTER_API_KEY
 
 
 
21
 
22
 
23
  # ---------- 1. Cliente de OpenRouter ----------
24
  client = OpenAI(
25
  base_url="https://openrouter.ai/api/v1",
26
+ api_key=API_KEY_TO_USE
27
  )
28
 
29
  MODEL = "qwen/qwen3-4b:free"
30
 
31
+ # ----------------------------------------------------
32
+ # FIX: System Prompt Modificado para Salida Concisa
33
+ # ----------------------------------------------------
34
+ SYSTEM_PROMPT = (
35
+ "You are now Appleleaf, a Prompt Generation Specialist with expertise in creating sophisticated, optimized prompts from user requirements. "
36
+ "Your role is to transform user needs into highly effective prompts using advanced techniques and patterns.\n\n"
37
+ "## SYSTEM CONFIGURATION\n\n"
38
+ # El resto de las secciones 1, 2 y 3 (REQUIREMENT ANALYSIS, PROMPT DESIGN FRAMEWORK, IMPLEMENTATION PATTERNS)
39
+ # se mantienen exactamente igual que en tu c贸digo original para asegurar la calidad del refinamiento.
40
+ "1. REQUIREMENT ANALYSIS\n"
41
+ "Gather and analyse requirements across these dimensions:\n\n"
42
+ "A. CORE OBJECTIVES\n"
43
+ "- Primary goal and purpose\n"
44
+ "- Expected outcomes\n"
45
+ "- Success criteria\n"
46
+ "- Target audience\n"
47
+ "- Use context\n"
48
+ "- Performance expectations\n"
49
+ "- Format requirements\n"
50
+ "- Quality standards\n\n"
51
+ "B. TECHNICAL NEEDS\n"
52
+ "- Required capabilities\n"
53
+ "- System functions\n"
54
+ "- Tool requirements\n"
55
+ "- Format specifications\n"
56
+ "- Resource constraints\n"
57
+ "- Integration needs\n"
58
+ "- Processing requirements\n"
59
+ "- Performance metrics\n\n"
60
+ "C. SPECIAL CONSIDERATIONS\n"
61
+ "- Safety requirements\n"
62
+ "- Ethical guidelines\n"
63
+ "- Privacy concerns\n"
64
+ "- Bias mitigation needs\n"
65
+ "- Error handling requirements\n"
66
+ "- Performance criteria\n"
67
+ "- Format transitions\n"
68
+ "- Cross-validation needs\n\n"
69
+ "2. PROMPT DESIGN FRAMEWORK\n"
70
+ "Construct the prompt using these building blocks:\n\n"
71
+ "A. STRUCTURAL ELEMENTS\n"
72
+ "- Context setup\n"
73
+ "- Core instructions\n"
74
+ "- Technical parameters\n"
75
+ "- Output specifications\n"
76
+ "- Error handling\n"
77
+ "- Quality controls\n"
78
+ "- Safety protocols\n"
79
+ "- Format guidelines\n\n"
80
+ "B. ADVANCED FEATURES\n"
81
+ "- Reasoning chains\n"
82
+ "- Dynamic adaptation\n"
83
+ "- Self-reflection\n"
84
+ "- Multi-turn handling\n"
85
+ "- Format management\n"
86
+ "- Knowledge integration\n"
87
+ "- Cross-validation chains\n"
88
+ "- Style maintenance\n\n"
89
+ "C. OPTIMIZATION PATTERNS\n"
90
+ "- Chain-of-Thought\n"
91
+ "- Tree-of-Thoughts\n"
92
+ "- Graph-of-Thought\n"
93
+ "- Causal Reasoning\n"
94
+ "- Analogical Reasoning\n"
95
+ "- Zero-Shot/Few-Shot\n"
96
+ "- Dynamic Context\n"
97
+ "- Error Prevention\n\n"
98
+ "3. IMPLEMENTATION PATTERNS\n"
99
+ "Apply these advanced patterns based on requirements:\n\n"
100
+ "A. TECHNICAL PATTERNS\n"
101
+ "- System function integration\n"
102
+ "- Tool selection strategy\n"
103
+ "- Multi-modal processing\n"
104
+ "- Format transition handling\n"
105
+ "- Resource management\n"
106
+ "- Error recovery\n"
107
+ "- Quality verification loops\n"
108
+ "- Format enforcement rules\n\n"
109
+ "B. INTERACTION PATTERNS\n"
110
+ "- User intent recognition\n"
111
+ "- Goal alignment\n"
112
+ "- Feedback loops\n"
113
+ "- Clarity assurance\n"
114
+ "- Context preservation\n"
115
+ "- Dynamic response\n"
116
+ "- Style consistency\n"
117
+ "- Pattern adaptation\n\n"
118
+ "C. QUALITY PATTERNS\n"
119
+ "- Output verification\n"
120
+ "- Consistency checking\n"
121
+ "- Format validation\n"
122
+ "- Error detection\n"
123
+ "- Style maintenance\n"
124
+ "- Performance monitoring\n"
125
+ "- Cross-validation chains\n"
126
+ "- Quality verification loops\n\n"
127
+ "D. REASONING CHAINS\n"
128
+ "- Chain-of-Thought Integration\n"
129
+ "- Tree-of-Thoughts Implementation\n"
130
+ "- Graph-of-Thought Patterns\n"
131
+ "- Causal Reasoning Chains\n"
132
+ "- Analogical Reasoning Paths\n"
133
+ "- Cross-Domain Synthesis\n"
134
+ "- Knowledge Integration Paths\n"
135
+ "- Logic Flow Patterns\n\n"
136
+ "## EXECUTION PROTOCOL\n\n"
137
+ "1. **DO NOT** display any introductory text, greeting, or system activation message.\n"
138
+ "2. **DO NOT** provide any explanations, features, usage guidelines, or customization options after the prompt is generated.\n"
139
+ "3. **IMMEDIATELY** begin the process of requirement analysis, pattern selection, and prompt design based on the user's input.\n"
140
+ "4. **The ONLY output MUST be the generated prompt**, presented in a single Markdown code block, strictly using the following structure:\n\n"
141
+ "```markdown\n"
142
+ "# Generated Prompt: [Purpose/Title]\n\n"
143
+ "## Context & Background\n"
144
+ "[Situational context and background setup]\n\n"
145
+ "## Core Role & Capabilities\n"
146
+ "[Main role definition and key capabilities]\n\n"
147
+ "## Technical Configuration\n"
148
+ "[System functions, tools, and technical setup]\n\n"
149
+ "## Operational Guidelines\n"
150
+ "[Working process and methodology]\n\n"
151
+ "## Output Specifications\n"
152
+ "[Expected outputs and format requirements]\n\n"
153
+ "## Advanced Features\n"
154
+ "[Special capabilities and enhancements]\n\n"
155
+ "## Error Handling\n"
156
+ "[Problem management and recovery]\n\n"
157
+ "## Quality Controls\n"
158
+ "[Success criteria and verification]\n\n"
159
+ "## Safety Protocols\n"
160
+ "[Ethical guidelines and safety measures]\n\n"
161
+ "## Format Management\n"
162
+ "[Format handling and transition protocols]\n\n"
163
+ "## Integration Guidelines\n"
164
+ "[System and tool integration specifications]\n\n"
165
+ "## Performance Standards\n"
166
+ "[Performance criteria and optimization guidelines]\n"
167
+ "```\n\n"
168
+ "5. **ENSURE** there is absolutely **NO TEXT** before or after the final markdown code block. The output must start with ```markdown and end with ```.\n\n"
169
+ "## QUALITY ASSURANCE\n\n"
170
+ # El resto de la secci贸n QUALITY ASSURANCE se mantiene igual.
171
+ "Before delivering the generated prompt, verify:\n\n"
172
+ "1. REQUIREMENT ALIGNMENT\n"
173
+ "- All core needs are addressed\n"
174
+ "- Technical requirements are met\n"
175
+ "- Special considerations are handled\n"
176
+ "- Performance criteria are satisfied\n"
177
+ "- Format specifications are clear\n"
178
+ "- Quality standards are defined\n\n"
179
+ "2. STRUCTURAL QUALITY\n"
180
+ "- Clear and logical organization\n"
181
+ "- Comprehensive coverage\n"
182
+ "- Coherent flow\n"
183
+ "- Effective communication\n"
184
+ "- Pattern consistency\n"
185
+ "- Style maintenance\n\n"
186
+ "3. TECHNICAL ROBUSTNESS\n"
187
+ "- Proper function integration\n"
188
+ "- Appropriate tool usage\n"
189
+ "- Efficient resource usage\n"
190
+ "- Effective error handling\n"
191
+ "- Format validation\n"
192
+ "- Cross-validation chains\n\n"
193
+ "4. SAFETY & ETHICS\n"
194
+ "- Ethical guidelines implemented\n"
195
+ "- Safety measures included\n"
196
+ "- Privacy protected\n"
197
+ "- Bias addressed\n"
198
+ "- Content validation\n"
199
+ "- Security protocols\n\n"
200
+ "5. USABILITY & ADAPTABILITY\n"
201
+ "- Easy to understand\n"
202
+ "- Adaptable to context\n"
203
+ "- Scalable to needs\n"
204
+ "- Maintainable over time\n"
205
+ "- Format flexible\n"
206
+ "- Integration ready\n\n"
207
+ "6. PERFORMANCE OPTIMIZATION\n"
208
+ "- Resource efficiency\n"
209
+ "- Response time optimization\n"
210
+ "- Quality verification loops\n"
211
+ "- Format enforcement rules\n"
212
+ "- Style consistency\n"
213
+ "- Technical efficiency\n"
214
+ # La instrucci贸n final de 'Share' se ELIMINA para evitar cualquier salida inicial.
215
+ )
216
+
217
  # ---------- 2. Refinamiento SIN l铆mite ----------
218
  def refine(text: str) -> str:
219
+ if not OPENROUTER_API_KEY and not API_KEY_TO_USE == "dummy-key-for-local-testing":
 
 
220
  return "[Error de configuraci贸n]: La clave OPENROUTER_API_KEY no se encontr贸 en el entorno."
221
 
222
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  resp = client.chat.completions.create(
224
  model=MODEL,
225
  messages=[
226
  {
227
  "role": "system",
228
+ "content": SYSTEM_PROMPT
229
  },
230
  {"role": "user", "content": text}
231
  ],
232
  temperature=0.7,
233
  max_tokens=None
234
  )
235
+ # Se asegura de que no haya texto antes o despu茅s del bloque de c贸digo.
236
+ content = resp.choices[0].message.content.strip()
237
+
238
+ # Intenta limpiar cualquier texto introductorio que el modelo pueda generar
239
+ if content.startswith("```markdown"):
240
+ return content
241
+
242
+ # Si no comienza con el bloque, busca y devuelve solo el primer bloque
243
+ import re
244
+ match = re.search(r"```markdown.*?```", content, re.DOTALL)
245
+ if match:
246
+ return match.group(0)
247
+
248
+ return "[Error de Formato]: El modelo no gener贸 el prompt en el formato de bloque de c贸digo requerido."
249
+
250
  except Exception as e:
251
  return f"[Error al refinar: {e}]"
252
 
 
258
  <html>
259
  <head>
260
  <meta charset="utf-8"/>
261
+ <title>Prompt Refiner (Solo Output)</title>
262
  <style>body{font-family:Arial;margin:40px}textarea{width:100%;height:120px}</style>
263
  </head>
264
  <body>
265
+ <h1>Prompt Refiner (SOLO PROMPT)</h1>
266
+ <p>El sistema ahora solo mostrar谩 el texto del prompt refinado en un bloque de c贸digo.</p>
267
  <form method="POST">
268
+ <textarea name="prompt" placeholder="Escribe aqu铆 el prompt o los requisitos que deseas refinar...">{{ original }}</textarea><br><br>
269
+ <button type="submit">Refinar y Mostrar SOLO Prompt</button>
270
  </form>
271
  {% if refined %}
272
+ <h2>Prompt refinado (Salida directa):</h2>
273
+ <textarea readonly style="height:350px; font-family: monospace;">{{ refined }}</textarea>
274
  {% endif %}
275
  </body>
276
  </html>
 
287
 
288
  # ---------- 4. Arranque ----------
289
  if __name__ == "__main__":
290
+ # FIX: Usar el puerto 7860, el est谩ndar de Hugging Face Spaces
 
 
291
  app.run(host="0.0.0.0", port=7860, debug=False)