cofaideveloper/chat.server
0
1import io2from fastapi import FastAPI, File, UploadFile3 4import subprocess5import os6import requests7import random8 9import shutil10import json11# from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline12from pydantic import BaseModel13from typing import Annotated14 15from fastapi import Form16 17 18import selenium19 20from selenium import webdriver21from selenium.webdriver import ChromeOptions22from selenium.webdriver.chrome.service import Service23import threading24import random25import string26import time27 28 29# from selenium.webdriver.firefox.options import Options30 31# options = FirefoxOptions()32# options.headless = True33 34# service = Service()35 36 37# driver = webdriver.Firefox(options= options,service=service)38# driver.get("https://yuntian-deng-chatgpt.hf.space/")39 40 41 42 43# driver.get("https://yuntian-deng-chatgpt.hf.space/")44 45 46class Query(BaseModel):47 text: str48 host:str49 50 51 52 53from fastapi import FastAPI, Request, Depends, UploadFile, File54from fastapi.exceptions import HTTPException55from fastapi.middleware.cors import CORSMiddleware56from fastapi.responses import JSONResponse57 58 59app = FastAPI()60 61app.add_middleware(62 CORSMiddleware,63 allow_origins=['*'],64 allow_credentials=True,65 allow_methods=['*'],66 allow_headers=['*'],67)68 69 70# cred = credentials.Certificate('key.json')71# app1 = firebase_admin.initialize_app(cred)72# db = firestore.client()73# data_frame = pd.read_csv('data.csv')74 75from selenium.webdriver.common.by import By76from pymongo.mongo_client import MongoClient77 78@app.on_event("startup")79async def startup_event():80 print("on startup")81 82 83 # t = threading.Thread(target=makeqimg) 84 # t.start()85 86 87 88 89 90mycol = None91 92 93@app.post("/url")94async def get_url(request: Request ):95 return "k"96 97 # data = await request.json()98 # text = data['url']99 # mongo_url=text100 # print("mongo url ",text)101 # global mycol102 # if mycol==None:103 # myclient = MongoClient(mongo_url)104 105 # try:106 # myclient.admin.command('ping')107 # print("Pinged your deployment. You successfully connected to MongoDB!")108 # except Exception as e:109 # print(e)110 111 # mydb = myclient['open-ai-api-keys']112 113 # mycol= mydb['key']114 # extract()115 116 117 118 119def extract():120 options = ChromeOptions()121 options.add_argument('--no-sandbox')122 options.add_argument('-headless')123 service = Service()124 driver = webdriver.Chrome(options= options,service=service)125 126 127 global mycol128 # global driver129 130 if True:131 # time.sleep(60)132 try:133 driver.get("https://talkai.info/chat/") 134 element = driver.find_element(By.CSS_SELECTOR,".chat")135 api_key = element.get_attribute("data-api-key")136 dict={"key":"open-ai"}137 mycol.delete_one(dict)138 dict={"key":"open-ai","value":api_key}139 mycol.insert_one(dict)140 print(api_key)141 driver.delete_all_cookies()142 driver.quit()143 144 except Exception as e: 145 print('error in extract ',e)146 pass147 # time.sleep(60)148 149 150 151from queue import Queue152chatq = Queue()153imgq= Queue()154 155 156def makeqchat():157 158 while chatq.qsize()<2:159 print("appending in chat queue")160 options = ChromeOptions()161 options.add_argument('--no-sandbox')162 options.add_argument('-headless')163 service = Service()164 driver = webdriver.Chrome(options= options,service=service)165 driver.get("https://talkai.info/chat/") 166 chatq.put(driver)167 168 169 170def makeqimg():171 172 while imgq.qsize()<2:173 print("appending in img queue")174 options = ChromeOptions()175 options.add_argument('--no-sandbox')176 options.add_argument('-headless')177 service = Service()178 driver = webdriver.Chrome(options= options,service=service)179 driver.get("https://talkai.info/image/") 180 imgq.put(driver)181 182 183 184 185 186 187 188@app.post("/")189async def get_answer(request: Request ):190 data = await request.json()191 192 text = data['text']193 host= ''194 195 temperature=-1196 197 try:198 temperature= data['temperature']199 temperature= float(temperature)200 temperature= round(temperature,1)201 202 except:203 print("No temperature")204 205 206 # N = 20207 # res = ''.join(random.choices(string.ascii_uppercase +208 # string.digits, k=N))209 # res= res+ str(time.time())210 211 id= ''212 213 214 # t = threading.Thread(target=do_ML, args=(id,text,host,0)) 215 # t.start()216 217 res= do_ML(id,text,host,0,temperature)218 219 220 dict={"ChatGPT":res}221 # dict= {"id":id}222 223 224 return JSONResponse(dict)225 226 227 228 229 230 231def do_ML(id:str,text:str,host:str, trycount:int,temperature:float):232 233 try:234 starttime=time.time()235 options = ChromeOptions()236 options.add_argument('--no-sandbox')237 options.add_argument('-headless')238 service = Service()239 driver = webdriver.Chrome(options= options,service=service)240 driver.get("https://talkai.info/chat/") 241 if temperature>=0 and temperature<=2:242 try:243 print("setting temperature ",temperature)244 while True:245 currtime= time.time()246 if(currtime>starttime+10):247 return "Requested Could not be proceed"248 249 try:250 setting_button = driver.find_element(By.ID, "openSettings")251 setting_button.click()252 break253 except:254 time.sleep(0.2)255 256 while True:257 currtime= time.time()258 if(currtime>starttime+10):259 return "Requested Could not be proceed"260 try:261 input_element = driver.find_element(By.CLASS_NAME,"styled-slider")262 new_value = temperature263 driver.execute_script("arguments[0].value = arguments[1]", input_element, new_value)264 break265 except:266 time.sleep(0.2)267 while True:268 currtime= time.time()269 if(currtime>starttime+10):270 return "Requested Could not be proceed"271 try:272 confirm_button = driver.find_element(By.CLASS_NAME, "settingsButtonConfirm")273 confirm_button.click()274 break275 except:276 time.sleep(0.2)277 except:278 print("could not set temperature")279 280 281 while True:282 currtime= time.time()283 if(currtime>starttime+10):284 return "Requested Could not be proceed"285 try:286 textarea = driver.find_element(By.CSS_SELECTOR, "textarea")287 textarea.send_keys(text)288 289 button = driver.find_element(By.CLASS_NAME, "sectionChatFormButton")290 button.click()291 break292 except:293 time.sleep(0.2)294 295 296 prev =""297 298 # time.sleep(2)299 while True:300 time.sleep(0.2)301 currtime= time.time()302 if(currtime>starttime+18.5):303 304 return "Requested Could not be proceed"305 306 value=""307 try:308 messages = driver.find_elements(By.CLASS_NAME, 'messageContain')309 last_message_contain = messages[len(messages)-2]310 value = last_message_contain.text311 value = value[8:len(value)]312 print(value)313 if value=="Please, wait...":314 continue315 except:316 continue317 318 319 320 driver.delete_all_cookies()321 driver.quit()322 return value323 324 325 326 except:327 print("Error")328 driver.delete_all_cookies()329 if trycount>3:330 331 return 332 driver.quit()333 return do_ML(id,text,host,trycount+1)334 335 336 337 338 339 340@app.post("/image")341async def get_answer(q: Query ):342 343 text = q.text344 host= q.host345 346 # N = 20347 # res = ''.join(random.choices(string.ascii_uppercase +348 # string.digits, k=N))349 # res= res+ str(time.time())350 351 id= ''352 353 # t = threading.Thread(target=do_ML2, args=(id,text,host,0)) 354 # t.start()355 356 url = do_ML2(id,text,host,0)357 358 dict= {"url":url}359 360 361 # dict= {"id":id}362 363 364 return JSONResponse(dict)365 366 367 368 369 370def do_ML2(id:str,text:str,host:str, trycount:int):371 372 try:373 starttime=time.time()374 375 options = ChromeOptions()376 options.add_argument('--no-sandbox')377 options.add_argument('-headless')378 service = Service()379 driver = webdriver.Chrome(options= options,service=service)380 driver.get("https://talkai.info/image/") 381 while True:382 currtime= time.time()383 if(currtime>starttime+10):384 return "Requested Could not be proceed"385 try:386 textarea = driver.find_element(By.CSS_SELECTOR, "textarea")387 textarea.send_keys(text)388 time.sleep(0.1)389 button = driver.find_element(By.CLASS_NAME, "sectionChatFormButton")390 button.click()391 break392 except:393 time.sleep(0.2)394 395 # time.sleep(2)396 while True:397 currtime= time.time()398 if(currtime>starttime+10):399 return "Requested Could not be proceed"400 401 time.sleep(0.2)402 currtime= time.time()403 if(currtime>starttime+18.5):404 405 return "Request Could not be proceed"406 try:407 messages = driver.find_elements(By.XPATH, "//div[@class='messageContain']/p/img")408 last_message_contain = messages[len(messages)-2]409 src = last_message_contain.get_attribute("src")410 print(src)411 412 driver.delete_all_cookies()413 driver.quit()414 415 return src416 break417 except:418 continue419 420 except:421 print("Error")422 driver.delete_all_cookies()423 if trycount>1:424 425 return "Request Could not be proceed"426 driver.quit()427 return do_ML2(id,text,host,trycount+1)428 429 430 431 432 433 434 435 