Lukeetah commited on
Commit
fe56eb4
·
verified ·
1 Parent(s): def3cc2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +201 -0
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import sqlite3
4
+ import json
5
+ from datetime import datetime
6
+ from huggingface_hub import HfApi, DatasetFilter
7
+ import datasets
8
+ from transformers import pipeline
9
+
10
+ # Configuración inicial
11
+ PERSISTENT_PATH = "/data" if os.path.exists("/data") else "./data"
12
+ os.makedirs(PERSISTENT_PATH, exist_ok=True)
13
+ DB_PATH = os.path.join(PERSISTENT_PATH, "colectivo.db")
14
+
15
+ # Modelos de IA eficientes (SmolVLM para dispositivos limitados)
16
+ TEXT_MODEL = "HuggingFaceH4/smol-lm-360M"
17
+ IMAGE_MODEL = "HuggingFaceH4/smol-vlm-256M"
18
+ AUDIO_MODEL = "openai/whisper-tiny"
19
+
20
+ # Inicialización diferida de pipelines
21
+ def get_text_pipeline():
22
+ return pipeline("text-generation", model=TEXT_MODEL)
23
+
24
+ def get_image_pipeline():
25
+ return pipeline("image-to-text", model=IMAGE_MODEL)
26
+
27
+ def get_audio_pipeline():
28
+ return pipeline("automatic-speech-recognition", model=AUDIO_MODEL)
29
+
30
+ # Base de datos para persistencia colectiva
31
+ def init_database():
32
+ conn = sqlite3.connect(DB_PATH)
33
+ cursor = conn.cursor()
34
+ cursor.execute("""
35
+ CREATE TABLE IF NOT EXISTS contribuciones (
36
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
37
+ usuario TEXT,
38
+ contenido TEXT,
39
+ tipo TEXT CHECK(tipo IN ('texto', 'imagen', 'audio')),
40
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
41
+ )
42
+ """)
43
+ cursor.execute("""
44
+ CREATE TABLE IF NOT EXISTS insights (
45
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
46
+ contribucion_id INTEGER,
47
+ insight TEXT,
48
+ FOREIGN KEY(contribucion_id) REFERENCES contribuciones(id)
49
+ )
50
+ """)
51
+ conn.commit()
52
+ return conn
53
+
54
+ # Procesamiento multimodal
55
+ def procesar_entrada(usuario, texto, imagen, audio):
56
+ conn = init_database()
57
+ cursor = conn.cursor()
58
+ timestamp = datetime.now().isoformat()
59
+
60
+ # Persistencia en base de datos
61
+ if texto:
62
+ cursor.execute("""
63
+ INSERT INTO contribuciones (usuario, contenido, tipo)
64
+ VALUES (?, ?, 'texto')
65
+ """, (usuario, texto))
66
+ elif imagen:
67
+ cursor.execute("""
68
+ INSERT INTO contribuciones (usuario, contenido, tipo)
69
+ VALUES (?, ?, 'imagen')
70
+ """, (usuario, imagen))
71
+ elif audio:
72
+ cursor.execute("""
73
+ INSERT INTO contribuciones (usuario, contenido, tipo)
74
+ VALUES (?, ?, 'audio')
75
+ """, (usuario, audio))
76
+
77
+ conn.commit()
78
+ contribucion_id = cursor.lastrowid
79
+
80
+ # Procesamiento con IA
81
+ insights = []
82
+ if texto:
83
+ pipe_texto = get_text_pipeline()
84
+ insight = pipe_texto(f"Analiza y sintetiza: {texto}", max_new_tokens=100)[0]['generated_text']
85
+ insights.append(insight)
86
+ elif imagen:
87
+ pipe_imagen = get_image_pipeline()
88
+ insight = pipe_imagen(imagen)[0]['generated_text']
89
+ insights.append(insight)
90
+ elif audio:
91
+ pipe_audio = get_audio_pipeline()
92
+ transcripcion = pipe_audio(audio)["text"]
93
+ pipe_texto = get_text_pipeline()
94
+ insight = pipe_texto(f"Resume y analiza: {transcripcion}", max_new_tokens=100)[0]['generated_text']
95
+ insights.append(insight)
96
+
97
+ # Guardar insights
98
+ for insight in insights:
99
+ cursor.execute("""
100
+ INSERT INTO insights (contribucion_id, insight)
101
+ VALUES (?, ?)
102
+ """, (contribucion_id, insight))
103
+
104
+ conn.commit()
105
+ conn.close()
106
+ return insights
107
+
108
+ # Interfaz colaborativa
109
+ def crear_interfaz():
110
+ with gr.Blocks(
111
+ title="SÍNTESIS: Inteligencia Colectiva Aumentada",
112
+ theme=gr.themes.Soft(primary_hue="emerald")
113
+ ) as interfaz:
114
+ gr.Markdown("# 🌐 SÍNTESIS: Plataforma de Inteligencia Colectiva Aumentada")
115
+ gr.Markdown("Conecta mentes humanas y artificiales para soluciones evolutivas")
116
+
117
+ with gr.Row():
118
+ with gr.Column(scale=1):
119
+ usuario = gr.Textbox(label="👤 Tu nombre (opcional)")
120
+ texto = gr.Textbox(label="📝 Contribución textual", lines=3)
121
+ imagen = gr.Image(label="🖼️ Subir imagen", type="filepath")
122
+ audio = gr.Audio(label="🎤 Grabación vocal", type="filepath")
123
+ btn_enviar = gr.Button("🚀 Publicar contribución")
124
+
125
+ with gr.Column(scale=2):
126
+ historico = gr.JSON(label="📚 Contribuciones colectivas")
127
+ btn_actualizar = gr.Button("🔄 Actualizar contribuciones")
128
+
129
+ with gr.Accordion("💡 Insights generados", open=False):
130
+ insights_output = gr.JSON()
131
+
132
+ # Eventos
133
+ btn_enviar.click(
134
+ procesar_entrada,
135
+ inputs=[usuario, texto, imagen, audio],
136
+ outputs=insights_output
137
+ )
138
+
139
+ btn_actualizar.click(
140
+ lambda: obtener_contribuciones(),
141
+ inputs=None,
142
+ outputs=historico
143
+ )
144
+
145
+ # Carga inicial
146
+ interfaz.load(
147
+ lambda: obtener_contribuciones(),
148
+ inputs=None,
149
+ outputs=historico
150
+ )
151
+
152
+ return interfaz
153
+
154
+ # Obtener contribuciones desde SQLite
155
+ def obtener_contribuciones(limit=20):
156
+ conn = sqlite3.connect(DB_PATH)
157
+ cursor = conn.cursor()
158
+ cursor.execute("""
159
+ SELECT c.id, c.usuario, c.contenido, c.tipo, c.timestamp, i.insight
160
+ FROM contribuciones c
161
+ LEFT JOIN insights i ON c.id = i.contribucion_id
162
+ ORDER BY c.timestamp DESC
163
+ LIMIT ?
164
+ """, (limit,))
165
+
166
+ resultados = []
167
+ for row in cursor.fetchall():
168
+ resultados.append({
169
+ "id": row[0],
170
+ "usuario": row[1] or "Anónimo",
171
+ "contenido": row[2],
172
+ "tipo": row[3],
173
+ "timestamp": row[4],
174
+ "insight": row[5]
175
+ })
176
+
177
+ conn.close()
178
+ return resultados
179
+
180
+ # Integración con Hugging Face Hub
181
+ def sincronizar_huggingface():
182
+ api = HfApi()
183
+ dataset = datasets.Dataset.from_dict({
184
+ "contribuciones": obtener_contribuciones(1000)
185
+ })
186
+
187
+ dataset.push_to_hub(
188
+ "colectivo_sintesis",
189
+ private=True,
190
+ token=os.environ.get("HF_TOKEN")
191
+ )
192
+
193
+ # Punto de entrada principal
194
+ if __name__ == "__main__":
195
+ init_database()
196
+ app = crear_interfaz()
197
+ app.launch(
198
+ server_name="0.0.0.0",
199
+ server_port=7860,
200
+ share=False
201
+ )