Adapters
finance
joseififif commited on
Commit
62cd34c
verified
1 Parent(s): 4c35924

Create backend/main.py

Browse files
Files changed (1) hide show
  1. backend/main.py +209 -0
backend/main.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from fastapi import FastAPI, HTTPException, BackgroundTasks
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from pydantic import BaseModel
6
+ from typing import Optional, Dict, Any
7
+ import numpy as np
8
+ from datetime import datetime
9
+ import uvicorn
10
+
11
+ # Importar m贸dulos
12
+ from solana_integration.diamond_token import DiamondTokenManager
13
+ from triton_server.inference import TritonInferenceEngine
14
+ from api.routes import router as api_router
15
+ from database.models import init_db, SessionLocal
16
+ from monitoring.metrics import MetricsCollector
17
+
18
+ app = FastAPI(title="Diamond AI Platform", version="1.0.0")
19
+
20
+ # Configurar CORS
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"],
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ # Inicializar componentes
30
+ diamond_token = DiamondTokenManager()
31
+ inference_engine = TritonInferenceEngine()
32
+ metrics = MetricsCollector()
33
+
34
+ class InferenceRequest(BaseModel):
35
+ prompt: str
36
+ wallet_address: Optional[str] = None
37
+ max_tokens: int = 200
38
+ temperature: float = 0.7
39
+ use_diamond_tokens: bool = True
40
+
41
+ class TrainingRequest(BaseModel):
42
+ dataset_path: str
43
+ epochs: int = 3
44
+ learning_rate: float = 1e-4
45
+ wallet_address: str
46
+
47
+ @app.on_event("startup")
48
+ async def startup_event():
49
+ """Inicializar la aplicaci贸n"""
50
+ await init_db()
51
+ await inference_engine.initialize()
52
+ await diamond_token.initialize()
53
+
54
+ # Iniciar monitoreo
55
+ asyncio.create_task(metrics.collect_system_metrics())
56
+
57
+ logging.info("馃殌 Diamond AI Platform iniciada")
58
+
59
+ @app.get("/")
60
+ async def root():
61
+ return {
62
+ "name": "Diamond AI Platform",
63
+ "version": "1.0.0",
64
+ "token_address": "5zJo2GzYRgiZw5j3SBNpuqVcGok35kT3ADwsw74yJWV6",
65
+ "wizardlm_model": "QuixiAI/WizardLM-7B-Uncensored"
66
+ }
67
+
68
+ @app.post("/inference")
69
+ async def generate_text(request: InferenceRequest, background_tasks: BackgroundTasks):
70
+ """
71
+ Endpoint de inferencia que utiliza tokens DIAMANTE
72
+ """
73
+ try:
74
+ # Verificar tokens si se requiere
75
+ if request.use_diamond_tokens and request.wallet_address:
76
+ has_tokens = await diamond_token.check_balance(request.wallet_address)
77
+ if not has_tokens:
78
+ raise HTTPException(
79
+ status_code=402,
80
+ detail="Tokens DIAMANTE insuficientes"
81
+ )
82
+
83
+ # Deducci贸n de tokens por uso
84
+ background_tasks.add_task(
85
+ diamond_token.deduct_tokens,
86
+ request.wallet_address,
87
+ amount=1 # 1 DIAMANTE por inferencia
88
+ )
89
+
90
+ # Generar texto con Trit贸n
91
+ response = await inference_engine.generate(
92
+ prompt=request.prompt,
93
+ max_tokens=request.max_tokens,
94
+ temperature=request.temperature
95
+ )
96
+
97
+ # Registrar m茅tricas
98
+ await metrics.record_inference(
99
+ wallet=request.wallet_address,
100
+ prompt_length=len(request.prompt),
101
+ response_length=len(response)
102
+ )
103
+
104
+ return {
105
+ "generated_text": response,
106
+ "tokens_used": len(response.split()),
107
+ "timestamp": datetime.utcnow().isoformat(),
108
+ "model": "WizardLM-7B-Uncensored"
109
+ }
110
+
111
+ except Exception as e:
112
+ logging.error(f"Error en inferencia: {e}")
113
+ raise HTTPException(status_code=500, detail=str(e))
114
+
115
+ @app.post("/train")
116
+ async def train_model(request: TrainingRequest):
117
+ """
118
+ Endpoint para fine-tuning con recompensas en DIAMANTE
119
+ """
120
+ # Verificar suficientes tokens para entrenamiento
121
+ required_tokens = 100 # 100 DIAMANTE para entrenamiento
122
+ balance = await diamond_token.get_balance(request.wallet_address)
123
+
124
+ if balance < required_tokens:
125
+ raise HTTPException(
126
+ status_code=402,
127
+ detail=f"Se requieren {required_tokens} tokens DIAMANTE"
128
+ )
129
+
130
+ # Iniciar entrenamiento en segundo plano
131
+ async def train_and_reward():
132
+ try:
133
+ # Ejecutar entrenamiento con Megatron
134
+ training_result = await megatron_training.fine_tune(
135
+ dataset_path=request.dataset_path,
136
+ epochs=request.epochs,
137
+ learning_rate=request.learning_rate
138
+ )
139
+
140
+ # Recompensar al usuario con tokens
141
+ if training_result["success"]:
142
+ reward = 50 # 50 DIAMANTE por contribuci贸n
143
+ await diamond_token.transfer(
144
+ from_wallet="platform_vault",
145
+ to_wallet=request.wallet_address,
146
+ amount=reward
147
+ )
148
+
149
+ # Guardar modelo entrenado
150
+ await save_trained_model(training_result["model_path"])
151
+
152
+ except Exception as e:
153
+ logging.error(f"Error en entrenamiento: {e}")
154
+
155
+ # Ejecutar en background
156
+ asyncio.create_task(train_and_reward())
157
+
158
+ return {
159
+ "message": "Entrenamiento iniciado",
160
+ "wallet": request.wallet_address,
161
+ "required_tokens": required_tokens,
162
+ "estimated_time": "2-4 horas"
163
+ }
164
+
165
+ @app.get("/token/balance/{wallet_address}")
166
+ async def get_balance(wallet_address: str):
167
+ """Consultar balance de tokens DIAMANTE"""
168
+ balance = await diamond_token.get_balance(wallet_address)
169
+ return {
170
+ "wallet": wallet_address,
171
+ "balance": balance,
172
+ "token_address": "5zJo2GzYRgiZw5j3SBNpuqVcGok35kT3ADwsw74yJWV6",
173
+ "token_name": "DIAMANTE"
174
+ }
175
+
176
+ @app.post("/token/transfer")
177
+ async def transfer_tokens(
178
+ from_wallet: str,
179
+ to_wallet: str,
180
+ amount: float,
181
+ private_key: str # En producci贸n usar autenticaci贸n segura
182
+ ):
183
+ """Transferir tokens DIAMANTE"""
184
+ try:
185
+ tx_signature = await diamond_token.transfer(
186
+ from_wallet=from_wallet,
187
+ to_wallet=to_wallet,
188
+ amount=amount,
189
+ private_key=private_key
190
+ )
191
+
192
+ return {
193
+ "success": True,
194
+ "tx_signature": tx_signature,
195
+ "from": from_wallet,
196
+ "to": to_wallet,
197
+ "amount": amount
198
+ }
199
+ except Exception as e:
200
+ raise HTTPException(status_code=400, detail=str(e))
201
+
202
+ if __name__ == "__main__":
203
+ uvicorn.run(
204
+ "main:app",
205
+ host="0.0.0.0",
206
+ port=8000,
207
+ reload=True,
208
+ log_level="info"
209
+ )