cryogenic22 commited on
Commit
b2607f4
·
verified ·
1 Parent(s): f0a6739

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -22
app.py CHANGED
@@ -1,34 +1,133 @@
1
  from fastapi import FastAPI, UploadFile, File
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.staticfiles import StaticFiles
4
- from fastapi.responses import FileResponse
5
  import pandas as pd
6
  from sentence_transformers import SentenceTransformer
7
  import numpy as np
8
- from typing import List, Dict
9
- import json
10
- from anthropic import Anthropic
11
  import os
12
 
13
  app = FastAPI()
14
- anthropic = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
15
  model = SentenceTransformer('all-MiniLM-L6-v2')
16
 
17
- app.add_middleware(
18
- CORSMiddleware,
19
- allow_origins=["*"],
20
- allow_methods=["*"],
21
- allow_headers=["*"],
22
- )
 
 
 
 
 
 
 
 
 
 
 
23
 
24
- @app.get("/")
25
- async def read_root():
26
- return FileResponse('static/index.html')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  @app.post("/api/process-file")
29
  async def process_file(file: UploadFile = File(...)):
30
  content = await file.read()
31
-
32
  with open(f"temp_{file.filename}", "wb") as f:
33
  f.write(content)
34
 
@@ -40,7 +139,6 @@ async def process_file(file: UploadFile = File(...)):
40
  text_reps.append(text_rep)
41
 
42
  embeddings = model.encode(text_reps)
43
-
44
  metadata = {
45
  'columns': list(df.columns),
46
  'row_count': len(df),
@@ -49,7 +147,6 @@ async def process_file(file: UploadFile = File(...)):
49
  }
50
 
51
  os.remove(f"temp_{file.filename}")
52
-
53
  return {
54
  'embeddings': embeddings.tolist(),
55
  'metadata': metadata,
@@ -61,6 +158,4 @@ async def query_data(query: str, embeddings: List[List[float]], k: int = 5):
61
  query_embedding = model.encode([query])[0]
62
  similarities = np.dot(embeddings, query_embedding)
63
  indices = np.argsort(similarities)[-k:][::-1].tolist()
64
- return {"similar_indices": indices}
65
-
66
- app.mount("/static", StaticFiles(directory="static"), name="static")
 
1
  from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.responses import HTMLResponse
 
 
3
  import pandas as pd
4
  from sentence_transformers import SentenceTransformer
5
  import numpy as np
6
+ from typing import List
 
 
7
  import os
8
 
9
  app = FastAPI()
 
10
  model = SentenceTransformer('all-MiniLM-L6-v2')
11
 
12
+ @app.get("/", response_class=HTMLResponse)
13
+ async def root():
14
+ return """
15
+ <!DOCTYPE html>
16
+ <html lang="en">
17
+ <head>
18
+ <meta charset="UTF-8">
19
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
20
+ <title>Analytics Dashboard</title>
21
+ <script src="https://cdn.tailwindcss.com"></script>
22
+ <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
23
+ <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
24
+ <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
25
+ <script src="https://unpkg.com/recharts@2.1.9/umd/Recharts.js"></script>
26
+ <script type="text/babel">
27
+ const { useState } = React;
28
+ const { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } = Recharts;
29
 
30
+ function App() {
31
+ const [data, setData] = useState(null);
32
+ const [query, setQuery] = useState('');
33
+ const [insights, setInsights] = useState([]);
34
+
35
+ const handleFileUpload = async (event) => {
36
+ const file = event.target.files[0];
37
+ const formData = new FormData();
38
+ formData.append('file', file);
39
+
40
+ const response = await fetch('/api/process-file', {
41
+ method: 'POST',
42
+ body: formData,
43
+ });
44
+ const result = await response.json();
45
+ setData(result);
46
+ };
47
+
48
+ const handleQuery = async () => {
49
+ if (!data || !query) return;
50
+
51
+ const response = await fetch('/api/query', {
52
+ method: 'POST',
53
+ headers: { 'Content-Type': 'application/json' },
54
+ body: JSON.stringify({
55
+ query,
56
+ embeddings: data.embeddings
57
+ }),
58
+ });
59
+
60
+ const result = await response.json();
61
+ const newInsights = result.similar_indices.map(idx => data.raw_data[idx]);
62
+ setInsights(newInsights);
63
+ };
64
+
65
+ return (
66
+ <div className="p-6 max-w-6xl mx-auto">
67
+ <h1 className="text-2xl font-bold mb-6">Data Analytics Dashboard</h1>
68
+ <div className="mb-6">
69
+ <label className="block mb-2 text-sm font-medium">Upload Data File</label>
70
+ <input
71
+ type="file"
72
+ onChange={handleFileUpload}
73
+ accept=".csv,.xlsx,.xls"
74
+ className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
75
+ />
76
+ </div>
77
+
78
+ {data && (
79
+ <div className="space-y-6">
80
+ <div>
81
+ <input
82
+ type="text"
83
+ value={query}
84
+ onChange={(e) => setQuery(e.target.value)}
85
+ placeholder="Ask a question about your data..."
86
+ className="w-full p-2 border rounded"
87
+ />
88
+ <button
89
+ onClick={handleQuery}
90
+ className="mt-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
91
+ >
92
+ Search
93
+ </button>
94
+ </div>
95
+
96
+ {insights.length > 0 && (
97
+ <div className="mt-6">
98
+ <h3 className="text-lg font-semibold mb-4">Related Insights</h3>
99
+ <div className="h-64">
100
+ <ResponsiveContainer width="100%" height="100%">
101
+ <BarChart data={insights}>
102
+ {Object.keys(insights[0] || {}).map((key) => (
103
+ <Bar key={key} dataKey={key} fill="#8884d8" />
104
+ ))}
105
+ <XAxis />
106
+ <YAxis />
107
+ <Tooltip />
108
+ </BarChart>
109
+ </ResponsiveContainer>
110
+ </div>
111
+ </div>
112
+ )}
113
+ </div>
114
+ )}
115
+ </div>
116
+ );
117
+ }
118
+
119
+ ReactDOM.render(<App />, document.getElementById('root'));
120
+ </script>
121
+ </head>
122
+ <body>
123
+ <div id="root"></div>
124
+ </body>
125
+ </html>
126
+ """
127
 
128
  @app.post("/api/process-file")
129
  async def process_file(file: UploadFile = File(...)):
130
  content = await file.read()
 
131
  with open(f"temp_{file.filename}", "wb") as f:
132
  f.write(content)
133
 
 
139
  text_reps.append(text_rep)
140
 
141
  embeddings = model.encode(text_reps)
 
142
  metadata = {
143
  'columns': list(df.columns),
144
  'row_count': len(df),
 
147
  }
148
 
149
  os.remove(f"temp_{file.filename}")
 
150
  return {
151
  'embeddings': embeddings.tolist(),
152
  'metadata': metadata,
 
158
  query_embedding = model.encode([query])[0]
159
  similarities = np.dot(embeddings, query_embedding)
160
  indices = np.argsort(similarities)[-k:][::-1].tolist()
161
+ return {"similar_indices": indices}