posix4e commited on
Commit
41d90ff
·
1 Parent(s): 89b7684

upgrade backend to support ios

Browse files
Files changed (1) hide show
  1. backend/backend.py +83 -40
backend/backend.py CHANGED
@@ -17,7 +17,6 @@ from pygments.lexers import get_lexer_by_name
17
  from sqlalchemy import JSON, Column, Integer, String, create_engine
18
  from sqlalchemy.ext.declarative import declarative_base
19
  from sqlalchemy.orm import Session, sessionmaker
20
- from sqlalchemy.sql import insert, select, text
21
  from uvicorn import Config, Server
22
 
23
  LANGS = [
@@ -39,8 +38,8 @@ class User(Base):
39
  return f"User(id={self.id}, uid={self.uid}"
40
 
41
 
42
- class History(Base):
43
- __tablename__ = "history"
44
 
45
  id = Column(Integer, primary_key=True, autoincrement=True)
46
  uid = Column(String, nullable=False)
@@ -48,7 +47,19 @@ class History(Base):
48
  answer = Column(String, nullable=False)
49
 
50
  def __repr__(self):
51
- return f"History(id={self.id}, uid={self.uid}, question={self.question}, answer={self.answer}"
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
 
54
  # Add a new table to store the commands
@@ -74,12 +85,32 @@ app = FastAPI(debug=True)
74
  app.add_middleware(GZipMiddleware, minimum_size=1000)
75
 
76
 
77
- # Add a new API endpoint to add commands to the queue
 
 
 
78
  class CommandItem(BaseModel):
79
  uid: str
80
  command: str
81
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  @app.post("/add_command")
84
  async def add_command(item: CommandItem):
85
  db: Session = SessionLocal()
@@ -90,11 +121,6 @@ async def add_command(item: CommandItem):
90
  return {"message": "Command added"}
91
 
92
 
93
- class EventItem(BaseModel):
94
- uid: str
95
- event: str
96
-
97
-
98
  @app.post("/send_event")
99
  async def send_event(item: EventItem):
100
  print(f"Received event from {item.uid}:\n{item.event}")
@@ -127,10 +153,6 @@ async def send_event(item: EventItem):
127
  }
128
 
129
 
130
- class RegisterItem(BaseModel):
131
- openai_key: str
132
-
133
-
134
  @app.post("/register")
135
  async def register(item: RegisterItem):
136
  db: Session = SessionLocal()
@@ -145,12 +167,6 @@ async def register(item: RegisterItem):
145
  return {"uid": new_user.uid}
146
 
147
 
148
- class AssistItem(BaseModel):
149
- uid: str
150
- prompt: str
151
- version: str
152
-
153
-
154
  @app.post("/assist")
155
  async def assist(item: AssistItem):
156
  db: Session = SessionLocal()
@@ -160,13 +176,15 @@ async def assist(item: AssistItem):
160
 
161
  # Call OpenAI
162
  openai.api_key = user.openai_key
163
- response = openai_text_call(item.prompt, model=item.version)
164
 
165
  # Update the last time assist was called
166
  user.last_assist = datetime.now()
167
 
168
  # Store the history
169
- new_history = History(uid=item.uid, question=item.prompt, answer=response["text"])
 
 
170
 
171
  db.add(new_history)
172
  db.commit()
@@ -177,27 +195,52 @@ async def assist(item: AssistItem):
177
  @app.get("/get_history/{uid}")
178
  async def get_history(uid: str):
179
  db: Session = SessionLocal()
180
- history = db.query(History).filter(History.uid == uid).all()
 
181
  commands = db.query(Command).filter(Command.uid == uid).all()
182
- if not history:
183
- raise HTTPException(status_code=400, detail="No history found for this uid")
184
- ret = {"history": [h.__dict__ for h in history]}
185
-
186
- if commands and len(commands) > 0:
187
- try:
188
- with open(f"{uid}_events.txt", "r") as f:
189
- events = f.read().split(",")
190
- except FileNotFoundError:
191
- events = None
192
-
193
- return {
194
- "events": events,
195
- "history": [h.__dict__ for h in history],
196
- "commands": [c.__dict__ for c in commands],
197
- }
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  else:
200
- return {"history": [h.__dict__ for h in history]}
 
201
 
202
 
203
  def assist_interface(uid, prompt, gpt_version):
 
17
  from sqlalchemy import JSON, Column, Integer, String, create_engine
18
  from sqlalchemy.ext.declarative import declarative_base
19
  from sqlalchemy.orm import Session, sessionmaker
 
20
  from uvicorn import Config, Server
21
 
22
  LANGS = [
 
38
  return f"User(id={self.id}, uid={self.uid}"
39
 
40
 
41
+ class AndroidHistory(Base):
42
+ __tablename__ = "android_history"
43
 
44
  id = Column(Integer, primary_key=True, autoincrement=True)
45
  uid = Column(String, nullable=False)
 
47
  answer = Column(String, nullable=False)
48
 
49
  def __repr__(self):
50
+ return f"AndroidHistory(question={self.question}, answer={self.answer}"
51
+
52
+
53
+ class BrowserHistory(Base):
54
+ __tablename__ = "browser_history"
55
+
56
+ id = Column(Integer, primary_key=True, autoincrement=True)
57
+ machineid = Column(String, nullable=False)
58
+ uid = Column(String, nullable=False)
59
+ url = Column(String, nullable=False)
60
+
61
+ def __repr__(self):
62
+ return f"BrowserHistory(machineid={self.machineid}, url={self.url}"
63
 
64
 
65
  # Add a new table to store the commands
 
85
  app.add_middleware(GZipMiddleware, minimum_size=1000)
86
 
87
 
88
+ class RegisterItem(BaseModel):
89
+ openai_key: str
90
+
91
+
92
  class CommandItem(BaseModel):
93
  uid: str
94
  command: str
95
 
96
 
97
+ class EventItem(BaseModel):
98
+ uid: str
99
+ event: str
100
+
101
+
102
+ class AssistItem(BaseModel):
103
+ uid: str
104
+ prompt: str
105
+ version: str
106
+
107
+
108
+ class SaveURLItem(BaseModel):
109
+ uid: str
110
+ machineid: str
111
+ url: str
112
+
113
+
114
  @app.post("/add_command")
115
  async def add_command(item: CommandItem):
116
  db: Session = SessionLocal()
 
121
  return {"message": "Command added"}
122
 
123
 
 
 
 
 
 
124
  @app.post("/send_event")
125
  async def send_event(item: EventItem):
126
  print(f"Received event from {item.uid}:\n{item.event}")
 
153
  }
154
 
155
 
 
 
 
 
156
  @app.post("/register")
157
  async def register(item: RegisterItem):
158
  db: Session = SessionLocal()
 
167
  return {"uid": new_user.uid}
168
 
169
 
 
 
 
 
 
 
170
  @app.post("/assist")
171
  async def assist(item: AssistItem):
172
  db: Session = SessionLocal()
 
176
 
177
  # Call OpenAI
178
  openai.api_key = user.openai_key
179
+ response = generate_quick_completion(item.prompt, item.version)
180
 
181
  # Update the last time assist was called
182
  user.last_assist = datetime.now()
183
 
184
  # Store the history
185
+ new_history = AndroidHistory(
186
+ uid=item.uid, question=item.prompt, answer=json.loads(str(response))
187
+ )
188
 
189
  db.add(new_history)
190
  db.commit()
 
195
  @app.get("/get_history/{uid}")
196
  async def get_history(uid: str):
197
  db: Session = SessionLocal()
198
+ history = db.query(BrowserHistory).filter(BrowserHistory.uid == uid).all()
199
+ browser_history = db.query(AndroidHistory).filter(AndroidHistory.uid == uid).all()
200
  commands = db.query(Command).filter(Command.uid == uid).all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
+ try:
203
+ with open(f"{uid}_events.txt", "r") as f:
204
+ events = f.read().split(",")
205
+ except FileNotFoundError:
206
+ events = ""
207
+
208
+ return {
209
+ "events": events,
210
+ "history": [h.__dict__ for h in history],
211
+ "browser_history": [h.__dict__ for h in browser_history],
212
+ "commands": [c.__dict__ for c in commands],
213
+ }
214
+
215
+
216
+ @app.post("/saveurl")
217
+ async def saveurl(item: SaveURLItem):
218
+ db: Session = SessionLocal()
219
+ new_browser_history = BrowserHistory(
220
+ uid=item.uid, machineid=item.machineid, url=item.url
221
+ )
222
+ db.add(new_browser_history)
223
+ db.commit()
224
+ db.refresh(new_browser_history)
225
+ return {"message": "Browser history saved"}
226
+
227
+
228
+ def generate_quick_completion(prompt, model):
229
+ dropdrown = model.split(":")
230
+ engine = dropdrown[0]
231
+ max_tokens = int(dropdrown[1])
232
+ if "gpt" in model:
233
+ message = [{"role": "user", "content": prompt}]
234
+ response = openai.ChatCompletion.create(
235
+ model=engine,
236
+ messages=message,
237
+ temperature=0.2,
238
+ max_tokens=max_tokens,
239
+ frequency_penalty=0.0,
240
+ )
241
  else:
242
+ raise Exception("Unknown model")
243
+ return response
244
 
245
 
246
  def assist_interface(uid, prompt, gpt_version):