Corran commited on
Commit
9b9424e
·
verified ·
1 Parent(s): 6d2f944

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -91
app.py CHANGED
@@ -1,104 +1,159 @@
1
- import os
 
 
 
2
 
3
- import solara
4
- from solara_enterprise import auth
5
- from reacton import ipyvuetify as rv
6
- from functools import partial
7
-
8
- os.environ['SOLARA_OAUTH_API_BASE_URL']="dev-r2bw2n3hwf72bni6.us.auth0.com" # replace with your domain
9
- os.environ['SOLARA_OAUTH_CLIENT_ID']="lQl2yjR7dr7XVbK480OJ2sfgoWf6U7s2" # replace with your client ID
10
- os.environ['SOLARA_OAUTH_CLIENT_SECRET']="BsGtc_GLEZgsv4DsZnSya4YhB38nm7ohJp5kobfOVb2X8CeT9XTHMOxnXR_djQMd" # not shown here, replace with your client secret
11
- os.environ['SOLARA_BASE_URL']='https://scrapalot-ebti.hf.space'
12
- os.environ['REPLICATE_API_TOKEN']='r8_YSD53gSw5IQbT8Fmnekc8ypEIuy28wN4IG45C'
13
 
14
- import replicate
15
 
16
- @solara.component
17
- def Message(message):
18
- icon = "mdi-robot" if message['user']=='Assistant' else 'mdi-account'
19
- icon = rv.Icon(children=[icon])
20
- user = rv.CardTitle(icon=icon,children=[solara.Columns([0.6,2,10],children=[icon,message['user'],rv.Spacer()])])
21
- text = rv.CardText(children=[message['text']])
22
- messageDiv = rv.Card(_class="mx-auto",width="100%",flat=True,children=[user,text])
23
- return messageDiv
24
-
25
- def Redo():
26
- message = messages.value[-2]['text']
27
- messages.set(messages.value[:-2])
28
- sendMessage(message)
29
 
30
  @solara.component
31
- def InputText():
32
- InputText = solara.InputText("Enter some text",value=input_text)
33
- rv.use_event(InputText,"keypress",partial(handleEnter))
34
- InputText
35
-
36
- def sendMessage(message):
37
- if auth.user.value:
38
- name = str(auth.user.value['userinfo']['name']).split(" ")[0]
39
  else:
40
- name = 'user'
41
- messages.set(messages.value+[{'user':name,'text':message}])
42
- prompt.value += f"[INST] {message} [/INST] \n"
43
- messages.set(messages.value+[{'user':'Assistant','text':''}])
44
- response = ''
45
- for token in replicate.stream(
46
- "meta/llama-2-7b-chat",
47
- input={
48
- "debug": False,
49
- "top_p": 1,
50
- "prompt": prompt.value,
51
- "temperature": 0.75,
52
- "system_prompt": f"You are a helpful, respectful and honest assistant. You are tasked with helping {name} with figuring out the correct European Binding Tariff Information for their shipment. Please address them by their name and their needs.",
53
- "max_new_tokens": 800,
54
- "min_new_tokens": -1,
55
- "prompt_template": "[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n{prompt} [/INST]",
56
- "repetition_penalty": 1
57
- },
58
- ):
59
- response += str(token)
60
- messages.set(messages.value[:-1]+[{'user':'Assistant', 'text':response}])
61
- prompt.value += f"{messages.value[-1]['text']}"
62
- print('Boom')
63
 
 
 
 
 
64
 
65
- def handleEnter(*args):
66
- if str(args[2]['key'])=='Enter':
67
- message = args[0].v_model
68
- print(message)
69
- input_text.set('')
70
- sendMessage(message)
71
 
 
 
72
 
73
- prompt = solara.reactive('')
74
- messages = solara.reactive([])
75
- input_text = solara.reactive('')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- @solara.component
78
- def ColumnLayout(children):
79
- solara.Columns([2,6,2],children=[solara.Column(),solara.Column(children),solara.Column()])
80
-
81
 
82
  @solara.component
83
- def Page():
84
-
85
- with solara.AppLayout(title="EBTI GPT"):
86
- solara.AppBarTitle(children=[])
87
- with rv.Card(flat=True):
88
- with ColumnLayout():
89
- if not auth.user.value:
90
- solara.Markdown(f"### Please Login ")
91
- solara.Button("Login", icon_name="mdi-login", href="/_solara/auth/login?redirect_uri=https%3A//scrapalot-ebti.hf.space/")
92
- else:
93
- userinfo = auth.user.value['userinfo']
94
- if 'name' in userinfo:
95
- solara.Markdown(f"### Welcome {userinfo['name']}")
96
- with ColumnLayout():
97
- rv.Card(flat=True,children=[Message(message) for message in messages.value])
98
- with ColumnLayout():
99
- InputText()
100
-
101
- if auth.user.value:
102
- with ColumnLayout():
103
- solara.Button("Logout", icon_name="mdi-logout", href=auth.get_logout_url())
104
- Page()
 
 
 
 
 
1
+ import solara, ipyreact
2
+ from pathlib import Path
3
+ import base64
4
+ import requests
5
 
6
+ def pdf_url_to_base64(url):
7
+ response = requests.get(url)
8
+ if response.status_code == 200:
9
+ pdf_bytes = response.content
10
+ base64_encoded = base64.b64encode(pdf_bytes).decode("utf-8")
11
+ return base64_encoded
12
+ else:
13
+ print("Failed to fetch PDF from URL:", url)
14
+ return None
 
15
 
 
16
 
17
+ ipyreact.define_module("ts-pdf", Path("./ts-pdf.mjs"))
18
+ ipyreact.define_import_map({
19
+ "pdfjs-dist": "https://esm.sh/pdfjs-dist@2.16.105/build/pdf.worker.js",
20
+ })
 
 
 
 
 
 
 
 
 
21
 
22
  @solara.component
23
+ def PDFViewer(type,pdf):
24
+ if type=="bytes":
25
+ pdf_bytes=pdf
 
 
 
 
 
26
  else:
27
+ pdf_bytes=pdf_url_to_base64(pdf)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ app = ipyreact.ValueWidget(_esm=
30
+ """
31
+ import React, { useEffect } from 'react';
32
+ import { AnnotEventDetail, CustomStampEventDetail, TsPdfViewer, TsPdfViewerOptions } from 'ts-pdf';
33
 
34
+ const PdfViewerComponent = () => {
35
+ useEffect(() => {
36
+ const mobileVhHack = () => {
37
+ const vh = window.innerHeight * 0.01;
38
+ document.documentElement.style.setProperty('--vh', `${vh}px`);
39
+ };
40
 
41
+ mobileVhHack();
42
+ window.addEventListener("resize", mobileVhHack);
43
 
44
+ return () => {
45
+ window.removeEventListener("resize", mobileVhHack);
46
+ };
47
+ }, []);
48
+
49
+ var arrayBuffer = base64ToArrayBuffer('"""+pdf_bytes+"""');
50
+
51
+ function base64ToArrayBuffer(base64) {
52
+ var binaryString = window.atob(base64);
53
+ var binaryLen = binaryString.length;
54
+ var bytes = new Uint8Array(binaryLen);
55
+ for (var i = 0; i < binaryLen; i++) {
56
+ var ascii = binaryString.charCodeAt(i);
57
+ bytes[i] = ascii;
58
+ }
59
+ return bytes;
60
+ }
61
+ var blob = new Blob([arrayBuffer], {type: "application/pdf"});
62
+ var link = window.URL.createObjectURL(blob);
63
+
64
+ useEffect(() => {
65
+ const run = async () => {
66
+ const options: TsPdfViewerOptions = {
67
+ containerSelector: "#pdf-main-container",
68
+ workerSource: "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.16.105/build/pdf.worker.js",
69
+ userName: "corran",
70
+ fileButtons: ["close", "save"],
71
+ comparableFileButtons: ["open", "close"],
72
+ annotChangeCallback: (detail: AnnotEventDetail) => {
73
+ if (detail.type === "focus" || detail.type === "select" || detail.type === "render") {
74
+ return;
75
+ }
76
+ console.log(detail);
77
+ },
78
+ customStampChangeCallback: (detail: CustomStampEventDetail) => {
79
+ // console.log(JSON.stringify(detail.stamp));
80
+ },
81
+ };
82
+ const viewer = new TsPdfViewer(options);
83
+ // viewer.importAnnotationsFromJson(dtos);
84
+ // }, 5000);
85
+ // for debug
86
+ window["pdfViewer"] = viewer;
87
+ await viewer.openPdfAsync(link);
88
+ };
89
+
90
+ run();
91
+
92
+ // Clean up function
93
+ return () => {
94
+ // Perform any cleanup of the effect here
95
+ };
96
+ }, []);
97
+
98
+ return (
99
+ <div style={{
100
+ position: "relative",
101
+ minWidth: "320px",
102
+ width: "100vw",
103
+ height: "calc(var(--vh, 1vh) * 100)",
104
+ margin: "0",
105
+ backgroundColor: "var(--tspdf-color-bg)",
106
+ transition: "height .25s ease"
107
+ }}>
108
+ <style>
109
+ {`
110
+ .abs-stretch {
111
+ position: absolute;
112
+ top: 0;
113
+ left: 0;
114
+ width: 100%;
115
+ height: 100%;
116
+ }
117
+ `}
118
+ </style>
119
+ <div className="test-container abs-stretch">
120
+ <div id="pdf-main-container" className="abs-stretch">
121
+ {/* Your PDF content will be rendered here */}
122
+ </div>
123
+ </div>
124
+ </div>
125
+ );
126
+ };
127
+
128
+ export default PdfViewerComponent;
129
+ """)
130
+ solara.display(app)
131
 
 
 
 
 
132
 
133
  @solara.component
134
+ def Reader():
135
+ solara.Style("""
136
+ #app > div > div:nth-child(2) >
137
+ div:nth-child(2){
138
+ display: none;
139
+ }
140
+ """)
141
+ router = solara.use_router()
142
+ path = router.path
143
+ if "bytes=" in path:
144
+ data=path.split("bytes=")[-1]
145
+ PDFViewer("bytes",data)
146
+ elif "url=" in path:
147
+ data=path.split("url=")[-1]
148
+ PDFViewer("url",data)
149
+ else:
150
+ solara.Markdown("Invalid PDF")
151
+ solara.Markdown(path)
152
+
153
+ routes = [
154
+ solara.Route(
155
+ "reader",
156
+ component=Reader,
157
+ ),
158
+ ]
159
+ Reader()