Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -29,6 +29,7 @@ try:
|
|
| 29 |
else:
|
| 30 |
print("AVISO: GEMINI_API_KEY não configurada. Gemini estará desativado para análise.")
|
| 31 |
except Exception as e:
|
|
|
|
| 32 |
print(f"ERRO ao inicializar o cliente Gemini: {e}. Funcionalidade de IA desativada.")
|
| 33 |
|
| 34 |
# 2. Configuração Groq
|
|
@@ -39,6 +40,7 @@ try:
|
|
| 39 |
else:
|
| 40 |
print("AVISO: GROQ_API_KEY não configurada. Groq estará desativado.")
|
| 41 |
except Exception as e:
|
|
|
|
| 42 |
print(f"ERRO ao inicializar o cliente Groq: {e}. Funcionalidade de IA desativada.")
|
| 43 |
|
| 44 |
|
|
@@ -80,17 +82,19 @@ def tts_proxy():
|
|
| 80 |
|
| 81 |
# --- ROTA 2: TRADUÇÃO RÁPIDA E CONTEXTO (IA) - USANDO GEMINI OU GROQ ---
|
| 82 |
|
| 83 |
-
def get_ai_response(provider, model_name, system_instruction, json_schema=None):
|
| 84 |
"""Função auxiliar para rotear a requisição LLM para o provedor selecionado."""
|
| 85 |
|
|
|
|
|
|
|
|
|
|
| 86 |
if provider == 'gemini':
|
| 87 |
if not genai_client:
|
| 88 |
raise Exception("Gemini client not initialized. GEMINI_API_KEY is missing.")
|
| 89 |
|
| 90 |
-
|
| 91 |
-
contents=[system_instruction]
|
| 92 |
|
| 93 |
-
# Configuração para resposta JSON estruturada
|
| 94 |
config = types.GenerateContentConfig()
|
| 95 |
if json_schema:
|
| 96 |
config = types.GenerateContentConfig(
|
|
@@ -119,9 +123,9 @@ def get_ai_response(provider, model_name, system_instruction, json_schema=None):
|
|
| 119 |
if not groq_client:
|
| 120 |
raise Exception("Groq client not initialized. GROQ_API_KEY is missing.")
|
| 121 |
|
| 122 |
-
# Para Groq, a instrução do sistema é o conteúdo
|
| 123 |
messages = [
|
| 124 |
-
{"role": "system", "content": system_instruction}
|
|
|
|
| 125 |
]
|
| 126 |
|
| 127 |
# Configuração para resposta JSON
|
|
@@ -151,25 +155,50 @@ def get_ai_response(provider, model_name, system_instruction, json_schema=None):
|
|
| 151 |
@app.route('/explain-proxy', methods=['POST'])
|
| 152 |
def explain_proxy():
|
| 153 |
"""
|
| 154 |
-
Usa o modelo LLM selecionado para fornecer explicação
|
| 155 |
"""
|
| 156 |
data = request.get_json()
|
| 157 |
word = data.get('word', '').strip()
|
| 158 |
-
context = data.get('context', '')
|
| 159 |
for_flashcard = data.get('for_flashcard', False)
|
| 160 |
-
#
|
| 161 |
model_provider, model_name = data.get('model', 'gemini:gemini-2.5-flash').split(':', 1)
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
|
| 164 |
-
return jsonify({"error": "No word or phrase selected."}), 400
|
| 165 |
-
|
| 166 |
if model_provider == 'gemini' and not genai_client:
|
| 167 |
return jsonify({"error": "GEMINI_API_KEY not configured. Cannot perform AI analysis."}), 503
|
| 168 |
if model_provider == 'groq' and not groq_client:
|
| 169 |
return jsonify({"error": "GROQ_API_KEY not configured. Cannot perform AI analysis."}), 503
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
|
|
|
|
|
|
| 173 |
|
| 174 |
# Define o schema JSON para Flashcards
|
| 175 |
flashcard_schema = {
|
|
@@ -178,15 +207,15 @@ def explain_proxy():
|
|
| 178 |
"term": {"type": "STRING", "description": "The selected word or phrase."},
|
| 179 |
"explanation": {"type": "STRING", "description": "A clear English definition or explanation."},
|
| 180 |
"translation": {"type": "STRING", "description": "The accurate Portuguese translation of the term/phrase."},
|
| 181 |
-
"example": {"type": "STRING", "description": "A new, helpful example sentence using the term/phrase."},
|
| 182 |
},
|
| 183 |
"required": ["term", "explanation", "translation", "example"]
|
| 184 |
}
|
| 185 |
|
| 186 |
try:
|
| 187 |
if for_flashcard:
|
| 188 |
-
#
|
| 189 |
-
system_instruction = system_instruction_base + " You must generate a single, highly relevant example sentence
|
| 190 |
|
| 191 |
# Para Groq, adicionamos a descrição do schema no prompt
|
| 192 |
if model_provider == 'groq':
|
|
@@ -196,18 +225,18 @@ def explain_proxy():
|
|
| 196 |
model_provider,
|
| 197 |
model_name,
|
| 198 |
system_instruction,
|
| 199 |
-
json_schema=flashcard_schema
|
| 200 |
)
|
| 201 |
|
| 202 |
-
# Verifica
|
| 203 |
if card_data and card_data.get('term') and card_data.get('translation') and card_data.get('example'):
|
| 204 |
return jsonify(card_data)
|
| 205 |
else:
|
| 206 |
raise Exception("AI returned empty or invalid structured data.")
|
| 207 |
|
| 208 |
else:
|
| 209 |
-
#
|
| 210 |
-
prompt = system_instruction_base + f" Provide a clear, one-sentence English explanation/definition, followed by an exact Portuguese translation, separated by a distinct marker like '---'.\nExample Format:\nDefinition in English.\n---\nTradução em Português."
|
| 211 |
|
| 212 |
text_response = get_ai_response(
|
| 213 |
model_provider,
|
|
@@ -255,4 +284,4 @@ def serve_index():
|
|
| 255 |
if __name__ == '__main__':
|
| 256 |
# Define o static_folder como o diretório atual para que o send_static_file funcione
|
| 257 |
app.static_folder = os.path.dirname(os.path.abspath(__file__))
|
| 258 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 29 |
else:
|
| 30 |
print("AVISO: GEMINI_API_KEY não configurada. Gemini estará desativado para análise.")
|
| 31 |
except Exception as e:
|
| 32 |
+
genai_client = None
|
| 33 |
print(f"ERRO ao inicializar o cliente Gemini: {e}. Funcionalidade de IA desativada.")
|
| 34 |
|
| 35 |
# 2. Configuração Groq
|
|
|
|
| 40 |
else:
|
| 41 |
print("AVISO: GROQ_API_KEY não configurada. Groq estará desativado.")
|
| 42 |
except Exception as e:
|
| 43 |
+
groq_client = None
|
| 44 |
print(f"ERRO ao inicializar o cliente Groq: {e}. Funcionalidade de IA desativada.")
|
| 45 |
|
| 46 |
|
|
|
|
| 82 |
|
| 83 |
# --- ROTA 2: TRADUÇÃO RÁPIDA E CONTEXTO (IA) - USANDO GEMINI OU GROQ ---
|
| 84 |
|
| 85 |
+
def get_ai_response(provider, model_name, system_instruction, custom_prompt=None, json_schema=None):
|
| 86 |
"""Função auxiliar para rotear a requisição LLM para o provedor selecionado."""
|
| 87 |
|
| 88 |
+
# O prompt base é o system_instruction, a menos que custom_prompt seja fornecido
|
| 89 |
+
prompt_to_use = custom_prompt if custom_prompt else system_instruction
|
| 90 |
+
|
| 91 |
if provider == 'gemini':
|
| 92 |
if not genai_client:
|
| 93 |
raise Exception("Gemini client not initialized. GEMINI_API_KEY is missing.")
|
| 94 |
|
| 95 |
+
contents=[prompt_to_use]
|
|
|
|
| 96 |
|
| 97 |
+
# Configuração para resposta JSON estruturada
|
| 98 |
config = types.GenerateContentConfig()
|
| 99 |
if json_schema:
|
| 100 |
config = types.GenerateContentConfig(
|
|
|
|
| 123 |
if not groq_client:
|
| 124 |
raise Exception("Groq client not initialized. GROQ_API_KEY is missing.")
|
| 125 |
|
|
|
|
| 126 |
messages = [
|
| 127 |
+
{"role": "system", "content": system_instruction},
|
| 128 |
+
{"role": "user", "content": prompt_to_use}
|
| 129 |
]
|
| 130 |
|
| 131 |
# Configuração para resposta JSON
|
|
|
|
| 155 |
@app.route('/explain-proxy', methods=['POST'])
|
| 156 |
def explain_proxy():
|
| 157 |
"""
|
| 158 |
+
Usa o modelo LLM selecionado para fornecer explicação, tradução, ou gerar atividades.
|
| 159 |
"""
|
| 160 |
data = request.get_json()
|
| 161 |
word = data.get('word', '').strip()
|
| 162 |
+
context = data.get('context', '') # Contexto local da frase
|
| 163 |
for_flashcard = data.get('for_flashcard', False)
|
| 164 |
+
# Novos parâmetros do frontend
|
| 165 |
model_provider, model_name = data.get('model', 'gemini:gemini-2.5-flash').split(':', 1)
|
| 166 |
+
context_focus = data.get('context_focus', 'General/Social') # Novo: contexto profissional/social
|
| 167 |
+
custom_prompt = data.get('custom_prompt', None) # Novo: prompt para geração de atividades
|
| 168 |
|
| 169 |
+
# 1. Checagem de disponibilidade e chaves
|
|
|
|
|
|
|
| 170 |
if model_provider == 'gemini' and not genai_client:
|
| 171 |
return jsonify({"error": "GEMINI_API_KEY not configured. Cannot perform AI analysis."}), 503
|
| 172 |
if model_provider == 'groq' and not groq_client:
|
| 173 |
return jsonify({"error": "GROQ_API_KEY not configured. Cannot perform AI analysis."}), 503
|
| 174 |
|
| 175 |
+
# Define a instrução do sistema base para todas as tarefas de IA
|
| 176 |
+
system_instruction_base = f"You are a professional English tutor and linguist focused on the context '{context_focus}'. All responses must be highly accurate and relevant to language learning."
|
| 177 |
+
|
| 178 |
+
# Se for uma requisição de Geração de Atividade (custom_prompt), use a instrução direta
|
| 179 |
+
if custom_prompt:
|
| 180 |
+
try:
|
| 181 |
+
# O get_ai_response usa o custom_prompt como conteúdo principal
|
| 182 |
+
text_response = get_ai_response(
|
| 183 |
+
model_provider,
|
| 184 |
+
model_name,
|
| 185 |
+
system_instruction=system_instruction_base,
|
| 186 |
+
custom_prompt=custom_prompt,
|
| 187 |
+
json_schema=None
|
| 188 |
+
)
|
| 189 |
+
# Para atividades, retornamos a resposta simples no campo 'explanation'
|
| 190 |
+
return jsonify({
|
| 191 |
+
"explanation": text_response,
|
| 192 |
+
"translation": "Activity Generated." # Marcador para o frontend
|
| 193 |
+
})
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"Erro na geração de atividade: {e}")
|
| 196 |
+
return jsonify({"error": f"AI activity generation failed: {e}"}), 500
|
| 197 |
+
|
| 198 |
|
| 199 |
+
# 2. Requisições de Contextualização (Clique Duplo/Flashcard)
|
| 200 |
+
if not word:
|
| 201 |
+
return jsonify({"error": "No word or phrase selected."}), 400
|
| 202 |
|
| 203 |
# Define o schema JSON para Flashcards
|
| 204 |
flashcard_schema = {
|
|
|
|
| 207 |
"term": {"type": "STRING", "description": "The selected word or phrase."},
|
| 208 |
"explanation": {"type": "STRING", "description": "A clear English definition or explanation."},
|
| 209 |
"translation": {"type": "STRING", "description": "The accurate Portuguese translation of the term/phrase."},
|
| 210 |
+
"example": {"type": "STRING", "description": "A new, helpful example sentence using the term/phrase, specifically tailored to the context of the user."},
|
| 211 |
},
|
| 212 |
"required": ["term", "explanation", "translation", "example"]
|
| 213 |
}
|
| 214 |
|
| 215 |
try:
|
| 216 |
if for_flashcard:
|
| 217 |
+
# 2a. Requisição para Flashcard (JSON Estruturado)
|
| 218 |
+
system_instruction = system_instruction_base + f" Analyze the term '{word}' in context: '{context}'. You must generate a single, highly relevant example sentence, and provide a clear, simple English definition. Translate the term/phrase accurately to Portuguese. The output MUST be a JSON object conforming to the provided schema."
|
| 219 |
|
| 220 |
# Para Groq, adicionamos a descrição do schema no prompt
|
| 221 |
if model_provider == 'groq':
|
|
|
|
| 225 |
model_provider,
|
| 226 |
model_name,
|
| 227 |
system_instruction,
|
| 228 |
+
json_schema=flashcard_schema # Usa o schema definido
|
| 229 |
)
|
| 230 |
|
| 231 |
+
# Verifica e retorna o JSON
|
| 232 |
if card_data and card_data.get('term') and card_data.get('translation') and card_data.get('example'):
|
| 233 |
return jsonify(card_data)
|
| 234 |
else:
|
| 235 |
raise Exception("AI returned empty or invalid structured data.")
|
| 236 |
|
| 237 |
else:
|
| 238 |
+
# 2b. Requisição para Modal (Explicação e Tradução Simples - Clique Duplo)
|
| 239 |
+
prompt = system_instruction_base + f" Analyze the term '{word}' in context: '{context}'. Provide a clear, one-sentence English explanation/definition, followed by an exact Portuguese translation, separated by a distinct marker like '---'.\nExample Format:\nDefinition in English.\n---\nTradução em Português."
|
| 240 |
|
| 241 |
text_response = get_ai_response(
|
| 242 |
model_provider,
|
|
|
|
| 284 |
if __name__ == '__main__':
|
| 285 |
# Define o static_folder como o diretório atual para que o send_static_file funcione
|
| 286 |
app.static_folder = os.path.dirname(os.path.abspath(__file__))
|
| 287 |
+
app.run(host='0.0.0.0', port=7860)
|