File size: 4,069 Bytes
bc16cc7
5f13892
 
 
 
 
 
bc16cc7
5f13892
 
 
 
 
 
 
 
 
 
 
 
bc16cc7
 
 
 
 
5f13892
 
 
 
 
bc16cc7
 
 
 
5f13892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e654377
5f13892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e654377
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import spaces  
import gradio as gr
import pandas as pd
import os
from sentence_transformers import SentenceTransformer
from datetime import datetime

# Загрузка ИИ-модели для перевода текста в векторы
model = SentenceTransformer('all-MiniLM-L6-v2')

DB_FILE = "dream_database.csv"

# Функция создания CSV, если его еще нет
def init_db():
    if not os.path.exists(DB_FILE):
        df = pd.DataFrame(columns=["Timestamp", "Alias", "ASC_Type", "Emotion", "Intensity", "Narrative", "Vector_Preview"])
        df.to_csv(DB_FILE, index=False)

init_db()

# СПЕЦИАЛЬНО ДЛЯ ZEROGPU: Эта функция запускает ИИ строго на видеокарте
@spaces.GPU
def get_embedding(text):
    return model.encode(text)

# Основная функция обработки данных
def process_entry(alias, asc_type, emotion, intensity, narrative):
    if not narrative.strip():
        return "Error: Please describe your experience.", "", pd.read_csv(DB_FILE).tail(5)
    
    # 1. Работа ИИ: используем функцию с поддержкой GPU
    embedding = get_embedding(narrative)
    
    # Берем первые 5 чисел для превью
    vector_preview = f"[{embedding[0]:.4f}, {embedding[1]:.4f}, {embedding[2]:.4f}, {embedding[3]:.4f}, {embedding[4]:.4f} ... 384 dimensions]"
    
    # 2. Сохраняем в базу данных
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    new_data = pd.DataFrame([[timestamp, alias, asc_type, emotion, intensity, narrative, vector_preview]], 
                            columns=["Timestamp", "Alias", "ASC_Type", "Emotion", "Intensity", "Narrative", "Vector_Preview"])
    
    new_data.to_csv(DB_FILE, mode='a', header=False, index=False)
    
    # 3. Обновляем таблицу для отображения
    updated_df = pd.read_csv(DB_FILE)
    
    success_msg = f"Thank you, {alias}! Your experience has been digitized and embedded into the DreamCode matrix."
    return success_msg, vector_preview, updated_df.tail(10)

# ----------------- ИНТЕРФЕЙС GRADIO -----------------
with gr.Blocks() as app:
    gr.Markdown("# 🌌 DreamCode: ASC Data Ingestion Portal (v0.1 Alpha)")
    gr.Markdown("Submit your Altered State of Consciousness (ASC) experiences. The underlying AI model instantly converts your narrative into multi-dimensional semantic vectors for cross-correlation analysis.")
    
    with gr.Row():
        with gr.Column():
            alias = gr.Textbox(label="Alias / Participant ID", placeholder="e.g., Subject-42 or Your Name")
            asc_type = gr.Dropdown(
                choices=["Ordinary Dream", "Lucid Dream (LD)", "Out-of-Body Experience (OBE)", "Near-Death Experience (NDE)", "Other"], 
                label="State of Consciousness"
            )
            emotion = gr.Radio(choices=["Positive", "Neutral", "Negative"], label="Core Emotional Tone")
            intensity = gr.Slider(minimum=1, maximum=3, step=1, label="Emotional Intensity (1-3)")
            
            narrative = gr.Textbox(label="Narrative / Description", lines=5, placeholder="Describe the imagery, geometry, architecture, or entities encountered...")
            
            submit_btn = gr.Button("Submit & Analyze", variant="primary")
            
        with gr.Column():
            status_output = gr.Textbox(label="System Status", interactive=False)
            vector_output = gr.Textbox(label="AI Semantic Vector Generation (Preview)", interactive=False)
            gr.Markdown("### Recent Global Database Entries (Anonymized Preview)")
            data_preview = gr.Dataframe(headers=["Timestamp", "Alias", "ASC_Type", "Emotion", "Intensity", "Narrative", "Vector_Preview"], interactive=False)

    submit_btn.click(
        fn=process_entry, 
        inputs=[alias, asc_type, emotion, intensity, narrative], 
        outputs=[status_output, vector_output, data_preview]
    )

app.launch(theme=gr.themes.Monochrome())