Cristobal299 commited on
Commit
9307481
·
verified ·
1 Parent(s): 30ab934

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +210 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import json
4
+ import requests
5
+ import tempfile
6
+ import gradio as gr
7
+
8
+ # ----------------------------------------------------------------------
9
+ # Configuration
10
+ # ----------------------------------------------------------------------
11
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
12
+ GROQ_ENDPOINT = "https://api.groq.com/v1/chat/completions"
13
+ MODEL_NAME = "llama-3.1-8b-instant" # default model, can be overridden via env if needed
14
+
15
+ # ----------------------------------------------------------------------
16
+ # Helper functions
17
+ # ----------------------------------------------------------------------
18
+ def call_groq(business_name: str) -> dict:
19
+ """
20
+ Calls Groq API with a prompt that asks for a JSON containing:
21
+ problems, solutions, explanation, eos_prompt.
22
+ Returns a dict with those keys or raises an Exception.
23
+ """
24
+ if not GROQ_API_KEY:
25
+ raise RuntimeError("GROQ_API_KEY not set in environment")
26
+
27
+ user_prompt = f"""You are an expert business analyst. Given the business name "{business_name}", list the top 5 classic problems, propose a solution for each, provide a detailed combined explanation, and finally output a ready-to-use EOS prompt in the following JSON format:
28
+ {{
29
+ "problems": ["..."],
30
+ "solutions": ["..."],
31
+ "explanation": "...",
32
+ "eos_prompt": "Title: ...\\nContext: ...\\nInstructions: ..."
33
+ }}
34
+ Only return the JSON object, no additional text."""
35
+ payload = {
36
+ "model": MODEL_NAME,
37
+ "messages": [{"role": "user", "content": user_prompt}],
38
+ "temperature": 0.7,
39
+ "max_tokens": 1024,
40
+ }
41
+ headers = {
42
+ "Authorization": f"Bearer {GROQ_API_KEY}",
43
+ "Content-Type": "application/json",
44
+ }
45
+
46
+ response = requests.post(
47
+ GROQ_ENDPOINT,
48
+ headers=headers,
49
+ json=payload,
50
+ timeout=10,
51
+ )
52
+ response.raise_for_status()
53
+ data = response.json()
54
+ # Expected structure: {"choices": [{"message": {"content": "..."} }]}
55
+ content = data["choices"][0]["message"]["content"]
56
+ # The model should return a JSON string
57
+ return json.loads(content)
58
+
59
+
60
+ def format_markdown_list(items):
61
+ """Convert a list of strings into a numbered markdown list."""
62
+ return "\n".join([f"{i+1}. {item}" for i, item in enumerate(items)])
63
+
64
+
65
+ def generate(business_name):
66
+ """
67
+ Main function called when the user clicks "Generar".
68
+ Returns:
69
+ problems_md, solutions_md, explanation_md, eos_prompt_code, json_path
70
+ """
71
+ if not business_name or not business_name.strip():
72
+ error_md = "### ❗ Error: El nombre del negocio no puede estar vacío."
73
+ return error_md, error_md, error_md, error_md, None
74
+
75
+ try:
76
+ result = call_groq(business_name.strip())
77
+ problems = result.get("problems", [])
78
+ solutions = result.get("solutions", [])
79
+ explanation = result.get("explanation", "")
80
+ eos_prompt = result.get("eos_prompt", "")
81
+
82
+ # Basic validation
83
+ if not (problems and solutions and explanation and eos_prompt):
84
+ raise ValueError("Respuesta incompleta del modelo.")
85
+
86
+ problems_md = f"### Problemas\n{format_markdown_list(problems)}"
87
+ solutions_md = f"### Soluciones\n{format_markdown_list(solutions)}"
88
+ explanation_md = f"### Explicación\n{explanation}"
89
+ eos_prompt_code = eos_prompt # will be shown in a gr.Code component
90
+
91
+ # Create temporary JSON file for download
92
+ export_dict = {
93
+ "business_name": business_name,
94
+ "problems": problems,
95
+ "solutions": solutions,
96
+ "explanation": explanation,
97
+ "eos_prompt": eos_prompt,
98
+ }
99
+ tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w", encoding="utf-8")
100
+ json.dump(export_dict, tmp_file, ensure_ascii=False, indent=2)
101
+ tmp_file.close()
102
+ json_path = tmp_file.name
103
+
104
+ return problems_md, solutions_md, explanation_md, eos_prompt_code, json_path
105
+
106
+ except requests.exceptions.RequestException as e:
107
+ err_md = f"### ❗ Error al conectar con Groq: {str(e)}"
108
+ return err_md, err_md, err_md, err_md, None
109
+ except (json.JSONDecodeError, ValueError) as e:
110
+ err_md = f"### ❗ Error al procesar la respuesta: {str(e)}"
111
+ return err_md, err_md, err_md, err_md, None
112
+ except Exception as e:
113
+ err_md = f"### ❗ Error inesperado: {str(e)}"
114
+ return err_md, err_md, err_md, err_md, None
115
+
116
+
117
+ # ----------------------------------------------------------------------
118
+ # Gradio Interface
119
+ # ----------------------------------------------------------------------
120
+ with gr.Blocks() as demo:
121
+ # Header
122
+ gr.Markdown(
123
+ "<h1 style='text-align:center; font-family:Roboto; font-weight:bold; font-size:24px;'>Business Problem Solver</h1>"
124
+ )
125
+
126
+ # Input form
127
+ with gr.Row():
128
+ business_input = gr.Textbox(
129
+ label="Nombre del negocio",
130
+ placeholder="Introduce el nombre del negocio",
131
+ lines=1,
132
+ max_lines=1,
133
+ elem_id="business-input",
134
+ )
135
+ generate_btn = gr.Button(
136
+ "Generar",
137
+ variant="primary",
138
+ elem_id="generate-btn",
139
+ )
140
+
141
+ # Output cards
142
+ with gr.Column():
143
+ problems_md = gr.Markdown(elem_id="problems-card")
144
+ solutions_md = gr.Markdown(elem_id="solutions-card")
145
+ explanation_md = gr.Markdown(elem_id="explanation-card")
146
+ eos_prompt_code = gr.Code(
147
+ label="Prompt EOS",
148
+ language="text",
149
+ show_copy_button=True,
150
+ elem_id="prompt-card",
151
+ )
152
+ download_btn = gr.DownloadButton(
153
+ label="Descargar JSON",
154
+ value=None,
155
+ elem_id="download-btn",
156
+ )
157
+
158
+ # Footer
159
+ gr.Markdown(
160
+ "<small>Más información sobre la API de Groq: <a href='https://groq.com/docs' target='_blank'>Documentación Groq</a></small>",
161
+ elem_id="footer",
162
+ )
163
+
164
+ # Interaction
165
+ generate_btn.click(
166
+ fn=generate,
167
+ inputs=[business_input],
168
+ outputs=[problems_md, solutions_md, explanation_md, eos_prompt_code, download_btn],
169
+ )
170
+
171
+ # ----------------------------------------------------------------------
172
+ # Custom CSS
173
+ # ----------------------------------------------------------------------
174
+ css = """
175
+ #business-input textarea {
176
+ border: 1px solid #CCCCCC;
177
+ }
178
+ #business-input textarea:focus {
179
+ border-color: #1E90FF;
180
+ }
181
+ #generate-btn {
182
+ background-color: #1E90FF;
183
+ color: white;
184
+ }
185
+ #generate-btn:hover {
186
+ background-color: #1C86EE;
187
+ }
188
+ #problems-card, #solutions-card, #explanation-card, #prompt-card {
189
+ padding: 15px;
190
+ border-radius: 8px;
191
+ margin-top: 10px;
192
+ }
193
+ #problems-card {
194
+ background-color: #F0F8FF;
195
+ }
196
+ #solutions-card {
197
+ background-color: #E6F7FF;
198
+ }
199
+ #explanation-card {
200
+ background-color: #FFFFFF;
201
+ }
202
+ #prompt-card {
203
+ background-color: #F5F5F5;
204
+ }
205
+ #download-btn {
206
+ margin-top: 10px;
207
+ }
208
+ """
209
+
210
+ demo.launch(css=css)