-
Notifications
You must be signed in to change notification settings - Fork 306
/
main.go
269 lines (225 loc) · 8.23 KB
/
main.go
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package main
import (
"flag"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
"compress/gzip"
"io"
"github.com/pashpashpash/vault/serverutil"
"github.com/pashpashpash/vault/vectordb"
"github.com/pashpashpash/vault/vectordb/pinecone"
"github.com/pashpashpash/vault/vectordb/qdrant"
"github.com/pashpashpash/vault/vault-web-server/postapi"
openai "github.com/sashabaranov/go-openai"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
)
const (
NegroniLogFmt = `{{.StartTime}} | {{.Status}} | {{.Duration}}
{{.Method}} {{.Path}}`
NegroniDateFmt = time.Stamp
)
var (
debugSite = flag.Bool(
"debug", false, "debug site")
port = flag.String(
"port", "8100", "server port")
siteConfig = map[string]string{
"DEBUG_SITE": "false",
}
)
func main() {
// Parse command line flags + override defaults
flag.Parse()
siteConfig["DEBUG_SITE"] = strconv.FormatBool(*debugSite)
rand.Seed(time.Now().UnixNano())
openaiApiKey := os.Getenv("OPENAI_API_KEY")
if len(openaiApiKey) == 0 {
log.Fatalln("MISSING OPENAI API KEY ENV VARIABLE")
}
openaiClient := openai.NewClient(openaiApiKey)
var vectorDB vectordb.VectorDB
var err error
qdrantApiEndpoint := os.Getenv("QDRANT_API_ENDPOINT")
if len(qdrantApiEndpoint) != 0 {
vectorDB, err = qdrant.New(qdrantApiEndpoint)
if err != nil {
log.Fatalln("ERROR INITIALIZING QDRANT:", err)
}
}
pineconeApiEndpoint := os.Getenv("PINECONE_API_ENDPOINT")
if len(pineconeApiEndpoint) != 0 {
pineconeApiKey := os.Getenv("PINECONE_API_KEY")
if len(pineconeApiKey) == 0 {
log.Fatalln("MISSING PINECONE API KEY ENV VARIABLE")
}
vectorDB, err = pinecone.New(pineconeApiEndpoint, pineconeApiKey)
if err != nil {
log.Fatalln("ERROR INITIALIZING PINECONE:", err)
}
}
if vectorDB == nil {
log.Fatalln("NO VECTOR DB CONFIGURED (QDRANT_API_ENDPOINT or PINECONE_API_ENDPOINT)")
}
handlerContext := postapi.NewHandlerContext(openaiClient, vectorDB)
// Configure main web server
server := negroni.New()
server.Use(negroni.NewRecovery())
l := negroni.NewLogger()
l.SetFormat(NegroniLogFmt)
l.SetDateFormat(NegroniDateFmt)
server.Use(l)
mx := mux.NewRouter()
// Path Routing Rules: [POST]
mx.HandleFunc("/api/questions", handlerContext.QuestionHandler).Methods("POST")
mx.HandleFunc("/upload", handlerContext.UploadHandler).Methods("POST")
// Path Routing Rules: Static Handlers
mx.HandleFunc("/github", StaticRedirectHandler("https://github.com/pashpashpash/vault"))
mx.PathPrefix("/").Handler(ReactFileServer(http.Dir(serverutil.WebAbs(""))))
// Start up web server
server.UseHandler(mx)
// if serving on https, need to provide self-signed certs
if *port == "443" {
go httpRedirect() // redirect all http to https
certFile := "/etc/letsencrypt/live/vault.pash.city/fullchain.pem"
keyFile := "/etc/letsencrypt/live/vault.pash.city/privkey.pem"
log.Println("[negroni] listening on :443")
log.Fatal(http.ListenAndServeTLS(":"+*port, certFile, keyFile, server))
} else {
server.Run("0.0.0.0:" + *port)
}
}
// / Takes a response writer Meta config and URL and servers the react app with the correct metadata
func ServeIndex(w http.ResponseWriter, r *http.Request, meta serverutil.SiteConfig) {
//Here we handle the possible dev environments or pass the basic Hostpath with "/" at the end for the / metadata for each site
var currentHost string
var currentSite string
// create local version of the Global SiteConfig variable to prevent editing concurrent variables.
var localSiteConfig = map[string]string{}
for key, element := range siteConfig {
localSiteConfig[key] = element
}
//set the host Manually when on local host
if r.Host == "localhost:8100" {
currentHost = "vault.pash.city"
currentSite = "vault"
} else {
currentHost = r.Host
currentSite = "vault"
}
currentpath := currentHost + r.URL.Path
//check if the currentpath has Metadata associated with it
//if no metadata is founnd use the default / route
ctx := r.Context()
defer ctx.Done()
// TODO fix metadata api
currentMetaData := meta.SitePath[currentpath]
localSiteConfig["PageTitle"] = currentMetaData.PageTitle
localSiteConfig["PageIcon"] = currentMetaData.PageIcon
localSiteConfig["MetaType"] = currentMetaData.MetaType
localSiteConfig["MetaTitle"] = currentMetaData.MetaTitle
localSiteConfig["MetaDescription"] = currentMetaData.MetaDescription
localSiteConfig["MetaUrl"] = "https://" + currentHost + r.URL.String()
localSiteConfig["MetaKeywords"] = currentMetaData.MetaKeywords
localSiteConfig["Site"] = currentSite
localSiteConfig["TwitterUsername"] = currentMetaData.TwitterUsername
/// Here we need to check the type and either add an Image meta tag or a video metatag depending on the result
if currentMetaData.MetaImage != "!" {
localSiteConfig["contentType"] = "og:image"
localSiteConfig["content"] = currentMetaData.MetaImage
} else {
localSiteConfig["contentType"] = "og:video"
if currentMetaData.MetaVideo != "!" {
localSiteConfig["content"] = currentMetaData.MetaVideo
} else { //
localSiteConfig["content"] = ""
log.Fatalln("Image and video tag missing from JSON template")
}
}
replaceEmpty := func(i string, r string) string {
if i == "" {
return r
}
return i
}
localSiteConfig["MetaTitle"] = replaceEmpty(localSiteConfig["MetaTitle"], "OP Question-Answer Stack")
localSiteConfig["MetaType"] = replaceEmpty(localSiteConfig["MetaType"], "website")
localSiteConfig["MetaDescription"] = replaceEmpty(localSiteConfig["MetaDescription"],
"Upload any number of files (pdf, text, epub) and use them as context when asking OpenAI questions.")
localSiteConfig["TwitterUsername"] = replaceEmpty(localSiteConfig["TwitterUsername"], "@pashmerepat")
localSiteConfig["MetaKeywords"] = replaceEmpty(localSiteConfig["MetaKeywords"], "OpenAI, Pinecone, ChatGPT")
localSiteConfig["PageTitle"] = replaceEmpty(localSiteConfig["PageTitle"], "The Vault | OP Question-Answer Stack")
localSiteConfig["PageIcon"] = replaceEmpty(localSiteConfig["Icon"], "/img/logos/vault-favicon.png")
localSiteConfig["content"] = replaceEmpty(localSiteConfig["content"], "https://i.imgur.com/6YSvyEV.png")
localSiteConfig["contentType"] = replaceEmpty(localSiteConfig["contentType"], "og:image")
localSiteConfig["ImageHeight"] = replaceEmpty(localSiteConfig["ImageHeight"], "1024")
localSiteConfig["ImageWidth"] = replaceEmpty(localSiteConfig["ImageWidth"], "1024")
t, err := template.ParseFiles(serverutil.WebAbs("index.html"))
config := struct {
Config map[string]string
}{
localSiteConfig,
}
if err != nil {
log.Fatalln("Critical error parsing index template!", err)
}
if err2 := t.Execute(w, config); err2 != nil {
log.Fatalln("Template execute error!", err)
}
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
// Forwards all traffic to React, except basic file serving
func ReactFileServer(fs http.FileSystem) http.Handler {
fsh := http.FileServer(fs)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//get the Metadata Config
jsonConfig := serverutil.GetConfig()
if path.Clean(r.URL.Path) == "/" || path.Clean(r.URL.Path) == "/index.html" {
ServeIndex(w, r, jsonConfig.SiteMetaData)
return
}
if _, err := os.Stat(serverutil.WebAbs(r.URL.Path)); os.IsNotExist(err) {
ServeIndex(w, r, jsonConfig.SiteMetaData)
return
}
// if gzip not possible serve as is
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fsh.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
fsh.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
})
}
func StaticRedirectHandler(to string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, to, http.StatusPermanentRedirect)
}
}
func httpRedirect() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
httpsURL := fmt.Sprintf("https://%s%s", r.Host, r.URL)
http.Redirect(w, r, httpsURL, http.StatusMovedPermanently)
})
log.Println("HTTP redirect server listening on :80")
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Fatalf("Error starting HTTP redirect server: %v", err)
}
}