amauricunha commited on
Commit
78e3636
·
verified ·
1 Parent(s): a9007fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -5
app.py CHANGED
@@ -41,6 +41,50 @@ except Exception as e:
41
  print(f"ERRO ao inicializar o cliente Groq: {e}.")
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # --- ROTAS PRINCIPAIS ---
45
 
46
  @app.route('/tts-proxy', methods=['POST'])
@@ -84,7 +128,7 @@ def explain_proxy():
84
  prompt = f"Analyze '{word}' in context: '{context}'. Generate a JSON for a flashcard. The 'gapped_sentence' must replace '{word}' with '______________'. You must strictly follow the JSON schema and provide valid, non-empty values for all fields."
85
  return jsonify(get_ai_text_response(model_provider, model_name, system_instruction_base, prompt, json_schema=schema))
86
 
87
- else: # Quick translation logic (not currently used in UI, but kept for potential future use)
88
  prompt = f"Analyze '{word}' in context: '{context}'. Provide a one-sentence English explanation, then '---', then the Portuguese translation."
89
  parts = get_ai_text_response(model_provider, model_name, system_instruction_base, prompt).split('---', 1)
90
  return jsonify({"explanation": parts[0].strip(), "translation": parts[1].strip() if len(parts) > 1 else 'N/A'})
@@ -92,7 +136,6 @@ def explain_proxy():
92
  except Exception as e:
93
  return jsonify({"error": f"AI analysis failed: {e}"}), 500
94
 
95
- # --- NOVA ROTA PARA FEEDBACK DE ATIVIDADES ---
96
  @app.route('/activity-feedback', methods=['POST'])
97
  def activity_feedback():
98
  data = request.get_json()
@@ -116,7 +159,6 @@ def activity_feedback():
116
  "Offer a corrected or improved version of their text. "
117
  "Structure your feedback with markdown for clarity (e.g., using ### Corrected Version)."
118
  )
119
-
120
  user_prompt = f"The original task was: \"{original_prompt}\"\n\nHere is the user's response:\n---\n{user_response}\n---\nPlease provide your feedback."
121
 
122
  try:
@@ -125,7 +167,6 @@ def activity_feedback():
125
  except Exception as e:
126
  return jsonify({"error": f"AI feedback failed: {e}"}), 500
127
 
128
-
129
  @app.route('/analyze-image', methods=['POST'])
130
  def analyze_image():
131
  if not genai_client: return jsonify({"error": "GEMINI_API_KEY not configured."}), 503
@@ -133,7 +174,7 @@ def analyze_image():
133
  base64_image = data.get('image')
134
  model_value = data.get('model', 'gemini:gemini-2.5-flash-latest')
135
 
136
- model_name = 'gemini-2.5-flash-latest'
137
  if model_value.startswith('gemini:'):
138
  model_name = model_value.split(':', 1)[1]
139
 
@@ -184,6 +225,7 @@ def generate_image():
184
  prompt = data.get('prompt')
185
  if not prompt: return jsonify({"error": "Image prompt is required."}), 400
186
  try:
 
187
  model = genai_client.GenerativeModel(model_name='gemini-2.5-flash-image-preview')
188
  response = model.generate_content(prompt)
189
  base64_image_data = response.parts[0].inline_data.data
@@ -194,6 +236,7 @@ def generate_image():
194
  # --- FUNÇÃO AUXILIAR E ROTA RAIZ ---
195
  def get_ai_text_response(provider, model_name, system_instruction, user_prompt, json_schema=None):
196
  if provider == 'gemini':
 
197
  model = genai_client.GenerativeModel(model_name, system_instruction=system_instruction)
198
  config = {}
199
  if json_schema:
 
41
  print(f"ERRO ao inicializar o cliente Groq: {e}.")
42
 
43
 
44
+ # --- NOVA ROTA PARA LISTAR MODELOS DINAMICAMENTE ---
45
+ @app.route('/list-models')
46
+ def list_models():
47
+ available_models = []
48
+ # CORREÇÃO: Lista de modelos Groq para geração de texto foi atualizada.
49
+ groq_text_models = [
50
+ "llama-3.1-8b-instant",
51
+ "llama-3.3-70b-versatile",
52
+ "openai/gpt-oss-120b",
53
+ "openai/gpt-oss-20b"
54
+ ]
55
+
56
+ try:
57
+ # Busca modelos Gemini
58
+ if genai_client:
59
+ for m in genai_client.list_models():
60
+ if 'generateContent' in m.supported_generation_methods:
61
+ model_name = m.name.replace("models/", "")
62
+ if "flash" in model_name or "pro" in model_name:
63
+ available_models.append({
64
+ "value": f"gemini:{model_name}",
65
+ "name": m.display_name
66
+ })
67
+
68
+ # Adiciona modelos Groq
69
+ if groq_client:
70
+ for model_id in groq_text_models:
71
+ display_name = model_id.split('/')[-1].replace('-instant', '').replace('-versatile', '')
72
+ available_models.append({
73
+ "value": f"groq:{model_id}",
74
+ "name": f"Groq: {display_name}"
75
+ })
76
+
77
+ except Exception as e:
78
+ print(f"Erro ao listar modelos: {e}")
79
+ # Retorna uma lista de fallback em caso de erro na API
80
+ return jsonify([
81
+ {"value": "gemini:gemini-2.5-flash-latest", "name": "Gemini 2.5 Flash (Fallback)"},
82
+ {"value": "groq:llama-3.1-8b-instant", "name": "Llama 3.1 8B (Fallback)"}
83
+ ])
84
+
85
+ return jsonify(available_models)
86
+
87
+
88
  # --- ROTAS PRINCIPAIS ---
89
 
90
  @app.route('/tts-proxy', methods=['POST'])
 
128
  prompt = f"Analyze '{word}' in context: '{context}'. Generate a JSON for a flashcard. The 'gapped_sentence' must replace '{word}' with '______________'. You must strictly follow the JSON schema and provide valid, non-empty values for all fields."
129
  return jsonify(get_ai_text_response(model_provider, model_name, system_instruction_base, prompt, json_schema=schema))
130
 
131
+ else:
132
  prompt = f"Analyze '{word}' in context: '{context}'. Provide a one-sentence English explanation, then '---', then the Portuguese translation."
133
  parts = get_ai_text_response(model_provider, model_name, system_instruction_base, prompt).split('---', 1)
134
  return jsonify({"explanation": parts[0].strip(), "translation": parts[1].strip() if len(parts) > 1 else 'N/A'})
 
136
  except Exception as e:
137
  return jsonify({"error": f"AI analysis failed: {e}"}), 500
138
 
 
139
  @app.route('/activity-feedback', methods=['POST'])
140
  def activity_feedback():
141
  data = request.get_json()
 
159
  "Offer a corrected or improved version of their text. "
160
  "Structure your feedback with markdown for clarity (e.g., using ### Corrected Version)."
161
  )
 
162
  user_prompt = f"The original task was: \"{original_prompt}\"\n\nHere is the user's response:\n---\n{user_response}\n---\nPlease provide your feedback."
163
 
164
  try:
 
167
  except Exception as e:
168
  return jsonify({"error": f"AI feedback failed: {e}"}), 500
169
 
 
170
  @app.route('/analyze-image', methods=['POST'])
171
  def analyze_image():
172
  if not genai_client: return jsonify({"error": "GEMINI_API_KEY not configured."}), 503
 
174
  base64_image = data.get('image')
175
  model_value = data.get('model', 'gemini:gemini-2.5-flash-latest')
176
 
177
+ model_name = 'gemini-2.5-flash-latest' # Default
178
  if model_value.startswith('gemini:'):
179
  model_name = model_value.split(':', 1)[1]
180
 
 
225
  prompt = data.get('prompt')
226
  if not prompt: return jsonify({"error": "Image prompt is required."}), 400
227
  try:
228
+ # Usa um modelo de imagem específico e estável
229
  model = genai_client.GenerativeModel(model_name='gemini-2.5-flash-image-preview')
230
  response = model.generate_content(prompt)
231
  base64_image_data = response.parts[0].inline_data.data
 
236
  # --- FUNÇÃO AUXILIAR E ROTA RAIZ ---
237
  def get_ai_text_response(provider, model_name, system_instruction, user_prompt, json_schema=None):
238
  if provider == 'gemini':
239
+ # Usa o model_name diretamente, que agora vem da lista dinâmica
240
  model = genai_client.GenerativeModel(model_name, system_instruction=system_instruction)
241
  config = {}
242
  if json_schema: