Files changed (1) hide show
  1. app.py +236 -69
app.py CHANGED
@@ -1,69 +1,236 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
- import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
- from tools.final_answer import FinalAnswerTool
7
-
8
- from Gradio_UI import GradioUI
9
-
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
- Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
- """
19
- return "What magic will you build ?"
20
-
21
- @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
- Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
- """
27
- try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
38
-
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
-
49
-
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
-
68
-
69
- GradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from datetime import date
3
+
4
+
5
+ # =========================
6
+ # FUNÇÕES
7
+ # =========================
8
+
9
+ def adicionar_transacao(tipo, descricao, categoria, valor, data, transacoes):
10
+ if not descricao:
11
+ return transacoes, atualizar_resumo(transacoes), "Digite uma descrição."
12
+
13
+ if not valor or valor <= 0:
14
+ return transacoes, atualizar_resumo(transacoes), "Digite um valor maior que zero."
15
+
16
+ nova_transacao = {
17
+ "tipo": tipo,
18
+ "descricao": descricao,
19
+ "categoria": categoria,
20
+ "valor": valor,
21
+ "data": data
22
+ }
23
+
24
+ transacoes.append(nova_transacao)
25
+
26
+ return (
27
+ transacoes,
28
+ atualizar_resumo(transacoes),
29
+ f"✅ {tipo} adicionada com sucesso!"
30
+ )
31
+
32
+
33
+ def atualizar_resumo(transacoes):
34
+ receitas = sum(
35
+ t["valor"] for t in transacoes
36
+ if t["tipo"] == "Receita"
37
+ )
38
+
39
+ despesas = sum(
40
+ t["valor"] for t in transacoes
41
+ if t["tipo"] == "Despesa"
42
+ )
43
+
44
+ saldo = receitas - despesas
45
+
46
+ texto = f"""
47
+ ## 💰 Resumo financeiro
48
+
49
+ **Receitas:** R$ {receitas:,.2f}
50
+
51
+ **Despesas:** R$ {despesas:,.2f}
52
+
53
+ **Saldo:** R$ {saldo:,.2f}
54
+
55
+ **Quantidade de lançamentos:** {len(transacoes)}
56
+ """
57
+
58
+ return texto
59
+
60
+
61
+ def mostrar_transacoes(transacoes):
62
+ if not transacoes:
63
+ return "Nenhuma transação cadastrada."
64
+
65
+ texto = "## 📋 Transações\n\n"
66
+
67
+ for i, t in enumerate(reversed(transacoes), 1):
68
+ sinal = "+" if t["tipo"] == "Receita" else "-"
69
+
70
+ texto += (
71
+ f"**{i}. {t['descricao']}** \n"
72
+ f"📅 {t['data']} | 🏷️ {t['categoria']} \n"
73
+ f"{sinal} R$ {t['valor']:,.2f} \n\n"
74
+ )
75
+
76
+ return texto
77
+
78
+
79
+ def adicionar_e_atualizar(
80
+ tipo,
81
+ descricao,
82
+ categoria,
83
+ valor,
84
+ data,
85
+ transacoes
86
+ ):
87
+ novas_transacoes, resumo, mensagem = adicionar_transacao(
88
+ tipo,
89
+ descricao,
90
+ categoria,
91
+ valor,
92
+ data,
93
+ transacoes
94
+ )
95
+
96
+ lista = mostrar_transacoes(novas_transacoes)
97
+
98
+ return (
99
+ novas_transacoes,
100
+ resumo,
101
+ lista,
102
+ mensagem,
103
+ "",
104
+ None
105
+ )
106
+
107
+
108
+ def limpar_transacoes():
109
+ transacoes = []
110
+
111
+ return (
112
+ transacoes,
113
+ atualizar_resumo(transacoes),
114
+ mostrar_transacoes(transacoes),
115
+ "🗑️ Todas as transações foram apagadas."
116
+ )
117
+
118
+
119
+ # =========================
120
+ # INTERFACE
121
+ # =========================
122
+
123
+ with gr.Blocks(
124
+ title="Meu Controle Financeiro"
125
+ ) as app:
126
+
127
+ transacoes = gr.State([])
128
+
129
+ gr.Markdown(
130
+ """
131
+ # 💰 Meu Controle Financeiro
132
+
133
+ Controle suas **receitas, despesas e saldo** de forma simples.
134
+ """
135
+ )
136
+
137
+ with gr.Row():
138
+
139
+ with gr.Column():
140
+
141
+ gr.Markdown("## ➕ Nova transação")
142
+
143
+ tipo = gr.Radio(
144
+ ["Receita", "Despesa"],
145
+ value="Despesa",
146
+ label="Tipo"
147
+ )
148
+
149
+ descricao = gr.Textbox(
150
+ label="Descrição",
151
+ placeholder="Ex: Supermercado"
152
+ )
153
+
154
+ categoria = gr.Dropdown(
155
+ [
156
+ "Alimentação",
157
+ "Transporte",
158
+ "Moradia",
159
+ "Contas",
160
+ "Lazer",
161
+ "Saúde",
162
+ "Educação",
163
+ "Salário",
164
+ "Investimentos",
165
+ "Outros"
166
+ ],
167
+ value="Outros",
168
+ label="Categoria"
169
+ )
170
+
171
+ valor = gr.Number(
172
+ label="Valor (R$)",
173
+ minimum=0
174
+ )
175
+
176
+ data = gr.Textbox(
177
+ label="Data",
178
+ value=str(date.today())
179
+ )
180
+
181
+ adicionar = gr.Button(
182
+ "➕ Adicionar",
183
+ variant="primary"
184
+ )
185
+
186
+ mensagem = gr.Markdown()
187
+
188
+ with gr.Column():
189
+
190
+ resumo = gr.Markdown(
191
+ atualizar_resumo([])
192
+ )
193
+
194
+ gr.Markdown("---")
195
+
196
+ lista = gr.Markdown(
197
+ "Nenhuma transação cadastrada."
198
+ )
199
+
200
+ apagar = gr.Button(
201
+ "🗑️ Apagar todas as transações"
202
+ )
203
+
204
+ adicionar.click(
205
+ adicionar_e_atualizar,
206
+ inputs=[
207
+ tipo,
208
+ descricao,
209
+ categoria,
210
+ valor,
211
+ data,
212
+ transacoes
213
+ ],
214
+ outputs=[
215
+ transacoes,
216
+ resumo,
217
+ lista,
218
+ mensagem,
219
+ descricao,
220
+ valor
221
+ ]
222
+ )
223
+
224
+ apagar.click(
225
+ limpar_transacoes,
226
+ outputs=[
227
+ transacoes,
228
+ resumo,
229
+ lista,
230
+ mensagem
231
+ ]
232
+ )
233
+
234
+
235
+ if __name__ == "__main__":
236
+ app.launch()