feature(#130): remove conflicts
Browse filesFiles changed (49)
- .gitignore+2
- Android/README.md-1
- Android/app/src/main/res/drawable/ic_attachment_48.xmlAdded+5
- Brain/README.md+1-6
- Brain/logs/activity.logDeleted-82
- Brain/src/commands/command.py+5-5
- Brain/src/common/assembler.py+16-1
- Brain/src/common/program_type.py+14-11
- Brain/src/common/utils.py+6
- Brain/src/gradio_debug.pyAdded+47
- Brain/src/model/requests/request_model.py+29
- Brain/src/rising_plugin/gmail/email_plugin.pyAdded+359
- Brain/src/rising_plugin/guardrails-config/actions/actions.py+1-107
- Brain/src/rising_plugin/guardrails-config/off-security.co+1-1
- Brain/src/rising_plugin/llm/llms.py+35-1
- Brain/src/rising_plugin/rails_validate.pyAdded+15
- Brain/src/rising_plugin/risingplugin.py+109-47
- Brain/src/router/api.py+91-3
- Brain/src/router/email_router.pyAdded+77
- Brain/src/router/train_router.py+27
- Brain/src/service/auto_task_service.py+14-2
- Brain/src/service/contact_service.py+67-1
- Brain/src/service/train_service.py+6
- Brain/tests/functional/test_api.py+26
- Extension/.idea/.gitignoreDeleted-5
- Extension/.idea/Extension.imlDeleted-12
- Extension/.idea/inspectionProfiles/Project_Default.xmlDeleted-6
- Extension/.idea/modules.xmlDeleted-8
- Extension/.idea/vcs.xmlDeleted-6
- Extension/src/pages/Content/modules/DraggablePanel.jsx+2
- Extension/src/pages/Panel/Message/index.css+14-8
- Extension/src/pages/Panel/Panel.css+15-2
- Extension/src/pages/Panel/Panel.jsx+24-12
- README.md+1-5
- WatchApp/WatchApp Watch App/Assets.xcassets/AccentColor.colorset/Contents.jsonDeleted-11
- WatchApp/WatchApp Watch App/Assets.xcassets/AppIcon.appiconset/Contents.jsonDeleted-13
- WatchApp/WatchApp Watch App/Assets.xcassets/Contents.jsonDeleted-6
- WatchApp/WatchApp Watch App/Components/ChatMessageRow.swiftAdded+57
- WatchApp/WatchApp Watch App/ContentView.swiftDeleted-73
- WatchApp/WatchApp Watch App/MainView.swiftAdded+28
- WatchApp/WatchApp Watch App/Pages/ChatView.swiftAdded+112
- WatchApp/WatchApp Watch App/Pages/SettingView.swiftAdded+46
- WatchApp/WatchApp Watch App/WatchAppApp.swift+1-1
- WatchApp/WatchApp.xcodeproj/project.pbxproj+59-20
- WatchApp/WatchApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedAdded+14
- WatchApp/WatchApp.xcodeproj/project.xcworkspace/xcuserdata/darkhorse.xcuserdatad/UserInterfaceState.xcuserstate
- WatchApp/WatchApp.xcodeproj/xcuserdata/darkhorse.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlistAdded+6
- app.py+14-2
- requirements.txt+5-2
123/Brain/firebase_cred.json/.ideaBrain/firebase_cred.json12345/Brain/firebase_cred.json/.ideaBrain/firebase_cred.jsonBrain/logs
22 unmodified lines2324252627282922 unmodified lines| Image Search System | A user can search image on Android local storage || Send SMS | If a user says that send SMS, mobile open SMS editor and a user can send SMS using the editor. |[[Rising Brain](https://github.com/ttt246/RisingBrain)]### Run locally- Copy google-services.json into app folder of project22 unmodified lines23242526272822 unmodified lines| Image Search System | A user can search image on Android local storage || Send SMS | If a user says that send SMS, mobile open SMS editor and a user can send SMS using the editor. |### Run locally- Copy google-services.json into app folder of project
12345<vector android:height="48dp" android:tint="#000000" android:viewportHeight="24" android:viewportWidth="24" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="@android:color/white" android:pathData="M2,12.5C2,9.46 4.46,7 7.5,7H18c2.21,0 4,1.79 4,4s-1.79,4 -4,4H9.5C8.12,15 7,13.88 7,12.5S8.12,10 9.5,10H17v2H9.41c-0.55,0 -0.55,1 0,1H18c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2H7.5C5.57,9 4,10.57 4,12.5S5.57,16 7.5,16H17v2H7.5C4.46,18 2,15.54 2,12.5z"/></vector>26 unmodified lines27282930313233344 unmodified lines3940414243444546474826 unmodified lines- 🌍 Support all web browsers to manipulate it automatically as its extension.- 🔗 Multiple API support (Web API for Free and Plus users, GPT-3.5, GPT-4, etc.).- 🔍 Integration to all mainstream search engines, and custom queries to support additional sites.[[Android Application](https://github.com/ttt246/RisingPhone)] [[Brrowser Extension](https://github.com/ttt246/Rising_Browser)] [[Rising Plugin](https://github.com/ttt246/Rising_Plugin)]#### 1.2 Feature- Chat with Rising AI as an assistant.4 unmodified lines- Manipulate all browsers with user's input(tab, page, search, scroll, or etc) and it will follow you to go on the real website or blog what you are thinking of.## 2. Installing / Getting startedInstall the latest version of rising-plugin package to use / custom something on what you want.```pip install rising-plugin```#### 2.1 how to run on localIt's a standard fastapi application so no configuration is needed beyond the included Procfile#### 2.2 Create firebase project26 unmodified lines272829303132334 unmodified lines38394041424326 unmodified lines- 🌍 Support all web browsers to manipulate it automatically as its extension.- 🔗 Multiple API support (Web API for Free and Plus users, GPT-3.5, GPT-4, etc.).- 🔍 Integration to all mainstream search engines, and custom queries to support additional sites.-#### 1.2 Feature- Chat with Rising AI as an assistant.4 unmodified lines- Manipulate all browsers with user's input(tab, page, search, scroll, or etc) and it will follow you to go on the real website or blog what you are thinking of.## 2. Installing / Getting started#### 2.1 how to run on localIt's a standard fastapi application so no configuration is needed beyond the included Procfile#### 2.2 Create firebase project
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081822023-06-11 01:39:05,597 ERROR sendNotification 2023-06-11 03:49:04,950 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-11 03:49:04,950 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-11 03:49:04,950 DEBUG System: You are a helpful assistant.2023-06-11 03:49:04,950 DEBUG 2023-06-11 03:49:04,950 DEBUG User: Who won the world series in 2020?2023-06-11 03:49:04,950 DEBUG 2023-06-11 03:49:04,950 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-11 03:49:04,950 DEBUG 2023-06-11 03:49:04,950 DEBUG User: Where was it played?2023-06-11 03:49:04,951 DEBUG 2023-06-11 03:49:04,951 DEBUG ----------- END OF CONTEXT ----------------2023-06-11 03:49:14,350 WARNING API Rate Limit Reached. Waiting 10 seconds... Error: 2023-06-11 03:49:34,004 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-11 03:49:34,004 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-11 03:49:34,004 DEBUG System: You are a helpful assistant.2023-06-11 03:49:34,004 DEBUG 2023-06-11 03:49:34,004 DEBUG User: Who won the world series in 2020?2023-06-11 03:49:34,004 DEBUG 2023-06-11 03:49:34,004 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-11 03:49:34,004 DEBUG 2023-06-11 03:49:34,004 DEBUG User: Where was it played?2023-06-11 03:49:34,004 DEBUG 2023-06-11 03:49:34,004 DEBUG ----------- END OF CONTEXT ----------------2023-06-11 03:50:02,195 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-11 03:50:02,196 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-11 03:50:02,196 DEBUG System: You are a helpful assistant.2023-06-11 03:50:02,196 DEBUG 2023-06-11 03:50:02,196 DEBUG User: Who won the world series in 2020?2023-06-11 03:50:02,197 DEBUG 2023-06-11 03:50:02,197 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-11 03:50:02,197 DEBUG 2023-06-11 03:50:02,197 DEBUG User: Where was it played?2023-06-11 03:50:02,197 DEBUG 2023-06-11 03:50:02,197 DEBUG ----------- END OF CONTEXT ----------------2023-06-11 03:52:01,682 WARNING API Rate Limit Reached. Waiting 10 seconds... Error: 2023-06-11 03:52:04,881 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-11 03:52:04,882 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-11 03:52:04,882 DEBUG System: You are a helpful assistant.2023-06-11 03:52:04,882 DEBUG 2023-06-11 03:52:04,882 DEBUG User: Who won the world series in 2020?2023-06-11 03:52:04,883 DEBUG 2023-06-11 03:52:04,883 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-11 03:52:04,883 DEBUG 2023-06-11 03:52:04,884 DEBUG User: Where was it played?2023-06-11 03:52:04,884 DEBUG 2023-06-11 03:52:04,884 DEBUG ----------- END OF CONTEXT ----------------2023-06-11 03:59:41,875 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-11 03:59:41,876 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-11 03:59:41,876 DEBUG System: You are a helpful assistant.2023-06-11 03:59:41,876 DEBUG 2023-06-11 03:59:41,876 DEBUG User: Who won the world series in 2020?2023-06-11 03:59:41,876 DEBUG 2023-06-11 03:59:41,876 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-11 03:59:41,876 DEBUG 2023-06-11 03:59:41,876 DEBUG User: Where was it played?2023-06-11 03:59:41,876 DEBUG 2023-06-11 03:59:41,876 DEBUG ----------- END OF CONTEXT ----------------2023-06-12 17:08:50,779 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-12 17:08:50,780 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-12 17:08:50,780 DEBUG System: You are a helpful assistant.2023-06-12 17:08:50,780 DEBUG 2023-06-12 17:08:50,780 DEBUG User: Who won the world series in 2020?2023-06-12 17:08:50,780 DEBUG 2023-06-12 17:08:50,780 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-12 17:08:50,780 DEBUG 2023-06-12 17:08:50,780 DEBUG User: Where was it played?2023-06-12 17:08:50,780 DEBUG 2023-06-12 17:08:50,780 DEBUG ----------- END OF CONTEXT ----------------2023-06-16 14:22:55,555 ERROR sendNotification json parsing or get completion error2023-06-16 14:23:59,508 ERROR sendNotification json parsing or get completion error2023-06-16 15:58:51,640 DEBUG Chat with AI on model : gpt-3.5-turbo2023-06-16 15:58:51,641 DEBUG ------------ CONTEXT SENT TO AI ---------------2023-06-16 15:58:51,641 DEBUG System: You are a helpful assistant.2023-06-16 15:58:51,642 DEBUG 2023-06-16 15:58:51,642 DEBUG User: Who won the world series in 2020?2023-06-16 15:58:51,642 DEBUG 2023-06-16 15:58:51,642 DEBUG Assistant: The Los Angeles Dodgers won the World Series in 2020.2023-06-16 15:58:51,642 DEBUG 2023-06-16 15:58:51,642 DEBUG User: Where was it played?2023-06-16 15:58:51,642 DEBUG 2023-06-16 15:58:51,642 DEBUG ----------- END OF CONTEXT ----------------61 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959661 unmodified lines"Search a image that #description",["#description"],True,).__str_json__(),Command("notification","send notification or alert","send that #notification",["#notification"],True,).__str_json__(),Command("sms","send a sms","",[],True,).__str_json__(),Command("browsing","search browser","Search something that #description",["#description"],True,).__str_json__(),Command("social","search something in social","Search something in twitter or facebook that #description",["#description"],True,).__str_json__(),]def get_all_commands(self) -> Any:61 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959661 unmodified lines"Search a image that #description",["#description"],True,),Command("notification","send notification or alert","send that #notification",["#notification"],True,),Command("sms","send a sms","",[],True,),Command("browsing","search browser","Search something that #description",["#description"],True,),Command("social","search something in social","Search something in twitter or facebook that #description",["#description"],True,),]def get_all_commands(self) -> Any:
56 unmodified lines575859606162635 unmodified lines69707156 unmodified lines"""mapping result type into json{"program": sms | contacts | browser | select_item_detail_info,"content": string}"""5 unmodified linesdef to_req_model(self, basic_req: BasicReq.Confs) -> ReqModel:return ReqModel(basic_req.to_json())56 unmodified lines575859606162635 unmodified lines69707172737475767778798081828384858656 unmodified lines"""mapping result type into json{"program": sms | contacts | browser | selectitemdetailinfo,"content": string}"""5 unmodified linesdef to_req_model(self, basic_req: BasicReq.Confs) -> ReqModel:return ReqModel(basic_req.to_json())"""mapping data from a ContactModel into json{"contactId": int,"displayName": string,"phoneNumbers": [string]}"""def to_contact_result_format(self, contact: ContactModel) -> Any:return {"contactId": contact.contact_id,"displayName": contact.display_name,"phoneNumbers": contact.phone_numbers,}
7 unmodified lines891011121314151617181920212223247 unmodified linesSMS = "sms"CONTACT = "contact"MESSAGE = "message"class BrowserType:OPEN_TAB = "open_tab"OPEN_TAB_SEARCH = "open_tab_search"CLOSE_TAB = "close_tab"PREVIOUS_PAGE = "previous_page"NEXT_PAGE = "next_page"SCROLL_UP = "scroll_up"SCROLL_DOWN = "scroll_down"SCROLL_TOP = "scroll_top"SCROLL_BOTTOM = "scroll_bottom"SELECT_ITEM_DETAIL_INFO = "select_item_detail_info"SELECT_ITEM = "select_item"MESSAGE = "message"7 unmodified lines891011121314151617181920212223242526277 unmodified linesSMS = "sms"CONTACT = "contact"MESSAGE = "message"AUTO_TASK = "autotask"RAILS_OFF_TOPIC = "rails_off_topic"class BrowserType:OPEN_TAB = "opentab"OPEN_TAB_SEARCH = "opentabsearch"CLOSE_TAB = "closetab"PREVIOUS_PAGE = "previouspage"NEXT_PAGE = "nextpage"SCROLL_UP = "scrollup"SCROLL_DOWN = "scrolldown"SCROLL_TOP = "scrolltop"SCROLL_BOTTOM = "scrollbottom"SELECT_ITEM_DETAIL_INFO = "selectitemdetailinfo"SELECT_ITEM = "selectitem"MESSAGE = "message"ASK_WEBSITE = "askwebsite"
39 unmodified lines4041424344451 unmodified line47484950515239 unmodified linesHUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")class ProgramType:BROWSER = "browser"ALERT = "alert"1 unmodified lineSMS = "sms"CONTACT = "contact"MESSAGE = "message"# validate json format39 unmodified lines404142434445464748491 unmodified line515253545556575839 unmodified linesHUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")# actions flag :True -> Directly with Category_promptACTION_FLAG = Trueclass ProgramType:BROWSER = "browser"ALERT = "alert"1 unmodified lineSMS = "sms"CONTACT = "contact"MESSAGE = "message"AUTO_TASK = "autotask"RAILS_OFF_TOPIC = "rails_off_topic"# validate json format
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""gradio implementaion"""# import gradio as gr# import requests# import json# from gradio.components import Textbox, Number## DEFAULT_UUID = "c40a09075d11940f"### def gradio_send_notification(uuid: str, query: str):# url = "http://localhost:7860/sendNotification"# data = {# "confs": {# "openai_key": "",# "pinecone_key": "",# "pinecone_env": "",# "firebase_key": "",# "settings": {"temperature": 0.6},# "token": "eSyP3i7ITZuq8hWn2qutTl:APA91bH1FtWkaTSJwuX4WKWAl3Q-ZFyrOw4UtMP4IfwuvNrHOThH7EvEGIhtguilLRyQNlLiXatEN0xntHAc8bbKobSGjge3wxIHlspbIWY_855CzONqaVdl3y3zOmgKZNnuhYi4gwbh",# "uuid": uuid,# },# "message": query,# }## response = requests.post(# url, data=json.dumps(data), headers={"Content-Type": "application/json"}# )# response = response.json()# return json.dumps(response["result"]), response["status_code"]### debug_send_notification = gr.Interface(# fn=gradio_send_notification,# inputs=[# Textbox(# label="UUID",# placeholder="Please input your UUID.",# value="c40a09075d11940f",# ),# Textbox(label="query", placeholder="Please input your prompt."),# ],# outputs=[# Textbox(label="Result"),# Number(label="Status Code"),# ],# allow_flagging="never",# )204 unmodified lines205206207204 unmodified linesid: strdata: TrainDatastatus: str204 unmodified lines205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236204 unmodified linesid: strdata: TrainDatastatus: str"""endpoint /auto_task/delete"""class AutoTaskDelete(BasicReq):class Body(BaseModel):reference_link: strdata: Body"""endpoint /read_emails"""class EmailReader(BasicReq):class Body(BaseModel):sender: strpwd: strimap_folder: strdata: Body"""endpoint : /contact/get_by_ids"""class GetContactsByIds(BasicReq):contactIds: list[str]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359import emailimport imaplibimport jsonimport mimetypesimport osimport reimport smtplibimport timefrom email.header import decode_headerfrom email.message import EmailMessage
from bs4 import BeautifulSoup
# email variablesEMAIL_SMTP_HOST = "smtp.gmail.com"EMAIL_SMTP_PORT = 587EMAIL_IMAP_SERVER = "imap.gmail.com"EMAIL_SIGNATURE = "This was sent by Brain Service"
class EmailPlugin: def send_email( self, sender: str, pwd: str, to: str, subject: str, body: str, to_send: bool ) -> str: return self.send_email_with_attachment_internal( sender=sender, pwd=pwd, to=to, title=subject, message=body, attachment=None, attachment_path=None, to_send=to_send, )
def send_email_with_attachment( self, sender: str, pwd: str, to: str, subject: str, body: str, filename: str, to_send: bool, ) -> str: attachment_path = filename attachment = os.path.basename(filename) return self.send_email_with_attachment_internal( sender=sender, pwd=pwd, to=to, title=subject, message=body, attachment_path=attachment_path, attachment=attachment, to_send=to_send, )
def send_email_with_attachment_internal( self, sender: str, pwd: str, to: str, title: str, message: str, attachment_path: str | None, attachment: str | None, to_send: bool, ) -> str: """Send an email
Args: sender (str): The email of the sender pwd (str): The password of the sender to (str): The email of the recipient title (str): The title of the email message (str): The message content of the email
Returns: str: Any error messages """ email_sender = sender email_password = pwd
msg = EmailMessage() msg["Subject"] = title msg["From"] = email_sender msg["To"] = to
signature = EMAIL_SIGNATURE if signature: message += f"\n{signature}"
msg.set_content(message)
if attachment_path: ctype, encoding = mimetypes.guess_type(attachment_path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed) ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) with open(file=attachment_path, mode="rb") as fp: msg.add_attachment( fp.read(), maintype=maintype, subtype=subtype, filename=attachment )
if to_send: smtp_host = EMAIL_SMTP_HOST smtp_port = EMAIL_SMTP_PORT # send email with smtplib.SMTP(host=smtp_host, port=smtp_port) as smtp: smtp.ehlo() smtp.starttls() smtp.login(user=email_sender, password=email_password) smtp.send_message(msg) smtp.quit() return f"Email was sent to {to}!" else: conn = self.imap_open( imap_folder="[Gmail]/Drafts", email_sender=email_sender, email_password=email_password, ) conn.append( mailbox="[Gmail]/Drafts", flags="", date_time=imaplib.Time2Internaldate(time.time()), message=str(msg).encode("UTF-8"), ) return f"Email went to [Gmail]/Drafts!"
def read_emails( self, sender: str, pwd: str, imap_folder: str = "inbox", imap_search_command: str = "UNSEEN", limit: int = 5, page: int = 1, ) -> str: """Read emails from an IMAP mailbox.
This function reads emails from a specified IMAP folder, using a given IMAP search command, limits, and page numbers. It returns a list of emails with their details, including the sender, recipient, date, CC, subject, and message body.
Args: sender (str): The email of the sender pwd (str): The password of the sender imap_folder (str, optional): The name of the IMAP folder to read emails from. Defaults to "inbox". imap_search_command (str, optional): The IMAP search command to filter emails. Defaults to "UNSEEN". limit (int, optional): Number of email's the function should return. Defaults to 5 emails. page (int, optional): The index of the page result the function should resturn. Defaults to 0, the first page.
Returns: str: A list of dictionaries containing email details if there are any matching emails. """ email_sender = sender imap_folder = self.adjust_imap_folder_for_gmail( imap_folder=imap_folder, email_sender=email_sender ) imap_folder = self.enclose_with_quotes(imap_folder) imap_search_ar = self.split_imap_search_command(imap_search_command) email_password = pwd
mark_as_seen = "False" if isinstance(mark_as_seen, str): mark_as_seen = json.loads(mark_as_seen.lower())
conn = self.imap_open( imap_folder=imap_folder, email_sender=email_sender, email_password=email_password, )
imap_keyword = imap_search_ar[0] if len(imap_search_ar) == 1: _, search_data = conn.search(None, imap_keyword) else: argument = self.enclose_with_quotes(imap_search_ar[1]) _, search_data = conn.search(None, imap_keyword, argument)
messages = [] for num in search_data[0].split(): if mark_as_seen: message_parts = "(RFC822)" else: message_parts = "(BODY.PEEK[])" _, msg_data = conn.fetch(message_set=num, message_parts=message_parts) for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_bytes(response_part[1])
# If the subject has unknown encoding, return blank if msg["Subject"] is not None: subject, encoding = decode_header(msg["Subject"])[0] else: subject = "" encoding = ""
if isinstance(subject, bytes): try: # If the subject has unknown encoding, return blank if encoding is not None: subject = subject.decode(encoding) else: subject = "" except [LookupError] as e: pass
body = self.get_email_body(msg) # Clean email body body = self.clean_email_body(body)
from_address = msg["From"] to_address = msg["To"] date = msg["Date"] cc = msg["CC"] if msg["CC"] else ""
messages.append( { "From": from_address, "To": to_address, "Date": date, "CC": cc, "Subject": subject, "Message Body": body, } )
conn.logout() if not messages: messages.append( { "From": "", "To": "", "Date": "", "CC": "", "Subject": "", "Message Body": "There are no Emails", } ) return json.dumps(messages)
# Confirm that integer parameters are the right type limit = int(limit) page = int(page)
# Validate parameter values if limit < 1: raise ValueError("Error: The message limit should be 1 or greater")
page_count = len(messages) // limit + (len(messages) % limit > 0)
if page < 1 or page > page_count: raise ValueError( "Error: The page value references a page that is not part of the results" )
# Calculate paginated indexes start_index = len(messages) - (page * limit + 1) end_index = start_index + limit start_index = max(start_index, 0)
# Return paginated indexes if start_index == end_index: return json.dumps([messages[start_index]]) else: return json.dumps(messages[start_index:end_index])
def adjust_imap_folder_for_gmail(self, imap_folder: str, email_sender: str) -> str: if "@gmail" in email_sender.lower() or "@googlemail" in email_sender.lower(): if "sent" in imap_folder.lower(): return '"[Gmail]/Sent Mail"' if "draft" in imap_folder.lower(): return "[Gmail]/Drafts" return imap_folder
def imap_open( self, imap_folder: str, email_sender: str, email_password: str ) -> imaplib.IMAP4_SSL: imap_server = EMAIL_IMAP_SERVER conn = imaplib.IMAP4_SSL(imap_server) conn.login(user=email_sender, password=email_password) conn.select(imap_folder) return conn
def get_email_body(self, msg: email.message.Message) -> str: if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() content_disposition = str(part.get("Content-Disposition")) if ( content_type == "text/plain" and "attachment" not in content_disposition ): # If the email body has unknown encoding, return null try: return part.get_payload(decode=True).decode() except UnicodeDecodeError as e: pass else: try: # If the email body has unknown encoding, return null return msg.get_payload(decode=True).decode() except UnicodeDecodeError as e: pass
def enclose_with_quotes(self, s): # Check if string contains whitespace has_whitespace = bool(re.search(r"\s", s))
# Check if string is already enclosed by quotes is_enclosed = s.startswith(("'", '"')) and s.endswith(("'", '"'))
# If string has whitespace and is not enclosed by quotes, enclose it with double quotes if has_whitespace and not is_enclosed: return f'"{s}"' else: return s
def split_imap_search_command(self, input_string): input_string = input_string.strip() parts = input_string.split(maxsplit=1) parts = [part.strip() for part in parts]
return parts
def clean_email_body(self, email_body): """Remove formating and URL's from an email's body
Args: email_body (str, optional): The email's body
Returns: str: The email's body without any formating or URL's """
# If body is None, return an empty string if email_body is None: email_body = ""
# Remove any HTML tags email_body = BeautifulSoup(email_body, "html.parser") email_body = email_body.get_text()
# Remove return characters email_body = "".join(email_body.splitlines())
# Remove extra spaces email_body = " ".join(email_body.split())
# Remove unicode characters email_body = email_body.encode("ascii", "ignore") email_body = email_body.decode("utf-8", "ignore")
# Remove any remaining URL's email_body = re.sub(r"http\S+", "", email_body)
return email_body12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812912 unmodified lines# See the License for the specific language governing permissions and# limitations under the License.import osimport jsonimport numpy as npfrom Brain.src.service.train_service import TrainServicefrom langchain.docstore.document import Documentfrom Brain.src.common.brain_exception import BrainExceptionfrom Brain.src.common.utils import (COMMAND_SMS_INDEXES,COMMAND_BROWSER_OPEN,PINECONE_INDEX_NAME,DEFAULT_GPT_MODEL,)from Brain.src.model.req_model import ReqModelfrom Brain.src.model.requests.request_model import BasicReqfrom Brain.src.rising_plugin.image_embedding import (query_image_text,)from Brain.src.rising_plugin.csv_embed import get_embedfrom nemoguardrails.actions import actionfrom Brain.src.rising_plugin.llm.falcon_llm import FalconLLMfrom Brain.src.rising_plugin.llm.gpt_llm import GptLLMfrom Brain.src.rising_plugin.llm.llms import (get_llm_chain,GPT_3_5_TURBO,GPT_4_32K,GPT_4,FALCON_7B,GPT_LLM_MODELS,)from Brain.src.rising_plugin.pinecone_engine import (get_pinecone_index_namespace,init_pinecone,)"""query is json string with below format{"query": string,"model": string,"uuid": string,"image_search": bool,"setting": {"host_name": string,"openai_key": string,"pinecone_key": string,"pinecone_env": string,"firebase_key": string,"firebase_env": string"settings": {"temperature": float},"token": string,"uuid": string,}}"""@action()async def general_question(query):"""init falcon model"""falcon_llm = FalconLLM()docs = []"""step 0-->: parsing parms from the json query"""try:json_query = json.loads(query)except Exception as ex:raise BrainException(BrainException.JSON_PARSING_ISSUE_MSG)query = json_query["query"]image_search = json_query["image_search"]page_content = json_query["page_content"]document_id = json_query["document_id"]setting = ReqModel(json_query["setting"])is_browser = json_query["is_browser"]docs.append(Document(page_content=page_content, metadata=""))""" 1. calling gpt model to categorize for all message"""chain_data = get_llm_chain(model=DEFAULT_GPT_MODEL, setting=setting).run(input_documents=docs, question=query)try:result = json.loads(chain_data)# check image query with only its textif result["program"] == "image":if image_search:result["content"] = {"image_name": query_image_text(result["content"], "", setting)}""" 2. check program is message to handle it with falcon llm """if result["program"] == "message":if is_browser:result["program"] = "ask_website"else:# """FALCON_7B:"""result["content"] = falcon_llm.query(question=query)return json.dumps(result)except ValueError as e:# Check sms and browser queryif document_id in COMMAND_SMS_INDEXES:return json.dumps({"program": "sms", "content": chain_data})elif document_id in COMMAND_BROWSER_OPEN:return json.dumps({"program": "browser", "content": "https://google.com"})if is_browser:return json.dumps({"program": "ask_website", "content": ""})return json.dumps({"program": "message", "content": falcon_llm.query(question=query)})12 unmodified lines131415161718192021222312 unmodified lines# See the License for the specific language governing permissions and# limitations under the License.import jsonfrom nemoguardrails.actions import action@action()async def general_question(query):return json.dumps({"program": "message", "content": query})
14 unmodified lines1516171814 unmodified linesbot explain cant off securitydefine bot explain cant off security'{"program": "message", "content": "Sorry, I cannot comment on anything which is relevant to the password or pin code."}'14 unmodified lines1516171814 unmodified linesbot explain cant off securitydefine bot explain cant off security'{"program": "rails_off_topic", "content": "Sorry, I cannot comment on anything which is relevant to the password or pin code."}'
19 unmodified lines20212223242535 unmodified lines6162636465666719 unmodified lines"""exception message"""EXCEPTION_MSG = f"The model is not correct. It should be in {LLM_MODELS}""""validate model"""35 unmodified lines"""check model"""llm = GptLLM(openai_key=setting.openai_key)if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:llm = GptLLM(model=model, openai_key=setting.openai_key)elif model == FALCON_7B:llm = FalconLLM(temperature=temperature, max_new_tokens=max_new_tokens)return llm19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565735 unmodified lines9394959697989910010119 unmodified lines"""exception message"""EXCEPTION_MSG = f"The model is not correct. It should be in {LLM_MODELS}""""prompt"""CATEGORY_PROMPT = """If user is going to say about a image with its description to search, please answer belowing json format. {"program": "image", "content": "description of the image that user is going to search"}If user is going to ask about a image, please answer belowing json format. {"program": "image", "content": "description of the image that user is going to search"}If user said that send sms or text, please answer belowing json format. {"program": "sms", "content": "ask who"}If user said that compose, write, or create an sms message, please answer belowing json format. {"program": "sms", "content": "ask who"}If user said that search contact with its description such as display name or phone number, please answer belowing json format. {"program": "contact", "content": "description of the contact that user is going to search"}If user said that open a tab, go to a tab, or open a page, please answer belowing json format. {"program": "opentab", "content": ""}If user said that open a tab and search, go to a tab and search, or open a page and search, please answer belowing json format. {"program": "opentabsearch", "content": "keyword that user is going to search"}If user said that close a tab, please answer belowing json format. {"program": "closetab", "content": ""}If user said that launch a browser or open a browser, please answer belowing json format. {"program": "browser", "content": "https://google.com"}If user said that go to a previous page, or open a previous page, please answer belowing json format. {"program": "previouspage", "content": ""}If user said that go to a next page, or open a next page, please answer belowing json format. {"program": "nextpage", "content": ""}If user said that scroll up, scroll up page, or page scroll up, please answer belowing json format. {"program": "scrollup", "content": ""}If user said that scroll down, scroll down page, page scroll down, please answer belowing json format. {"program": "scrolldown", "content": ""}If user said that scroll top, scroll top page, or scroll top of page, please answer belowing json format. {"program": "scrolltop", "content": ""}If user said that scroll bottom, scroll bottom page, or scroll bottom of page, please answer belowing json format. {"program": "scrollbottom", "content": ""}If user is going to select an item, an article or a website with its description in a web browser, please answer belowing json format. {"program": "selectitemdetailinfo", "content": "the description of an item, an article or a website in a browser"}If user said that ask about the content in website, for example, if users ask something like 'what is #query in this website?' or 'Can you tell me about #query based on this website?', please answer belowing json format. {"program": "askwebsite", "content": ""}If user said that open a website using web browsers, please answer belowing json format. The url user is going to open can exist or not. If user doesn\\'t say exact url and want to open some sites, you have to find the best proper url. If user didn\\'t say any url and you can't find proper url, please set website url to "https://www.google.com". {"program": "browser", "url": "website url that user is going to open"}If users are going to ask something based on the data of website, please answer belowing json format. {"program": "askwebsite", "content": ""}If user is going to set or create alarm with time and label, please answer belowing json format.\n {"program": "alarm", "content": {"type":"create", "time":"please set time as 24-hours format that user is going to set. If user did not provide any alarm time, set "0:0"", "label":"please set label that user is going to set. If user did not provide any label, set "alarm""}}\n This is example data.\n User: Set an alarm.\n AI: {"program":"alarm", "content": {"type":"create", "time":"0:0", "label":"alarm"}}\n User: Set an alarm with label as "wake up".\n AI: {"program":"alarm", "content": {"type":"create", "time":"0:0", "label":"wake up"}}\n User: Set an alarm for 5:00 AM.\n AI: {"program":"alarm", "content": {"type":"create", "time":"5:00", "label":"alarm"}}\n User: Set an alarm for 5:00 PM with label as "wake up".\n AI: {"program":"alarm", "content": {"type":"create", "time":"17:00", "label":"wake up"}}If user is going to read email or message, please answer belowing json format. {"program": "reademail", "content": ""}If user is going to send email or message, please answer belowing json format. {"program": "sendemail", "content": ""}If user is going to compose, write, or create an email, please answer belowing json format. {"program": "writeemail", "content": ""}User wants to help organization in achieving its goals, which bridges the gap between the user is (present) and where he/she wants to go (future), or that is deciding in advance what to do, how to do when to do it and by whom it is to be done. Also the description ensures in thoughts and actions, work is carried on smoothly without any confusion and misunderstanding. \n And it can be done for the future and the future is full of uncertainties. \n So it looks like to make a decision as well. It helps make rational decisions by choosing the best most profitable alternative which may bring lower cost, adaptable to the organization and situations. \n If user is going to say about planning strategy, or something like that , please answer belowing json format. {"program": "autotask", "content": ""}If all of above is not correct, please give the most appropriate answer to the user's question. Please answer belowing json format. {"program":"message", "content":"your answer"}If users are going to know about real-time capabilities such as News, Weather, Stocks, Booking, Planning, or etc, then please answer belowing json format. {"program": "autotask", "content": ""}If your answer is not correct with the program type which mentioned in this rules, please answer belowing json format. {"program": "autotask", "content": ""}""""""validate model"""35 unmodified lines"""check model"""llm = GptLLM(openai_key=setting.openai_key)if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:llm = GptLLM(model=model, openai_key=setting.openai_key, temperature=temperature)elif model == FALCON_7B:llm = FalconLLM(temperature=temperature, max_new_tokens=max_new_tokens)return llm
123456789101112131415"""validate rails result:checking with program whether is it message or rails_off_topic"""import json
from Brain.src.common.program_type import ProgramType
def validate_rails(data: str) -> bool: try: json_obj = json.loads(data["content"]) if json_obj["program"] == ProgramType.RAILS_OFF_TOPIC: return False return True except Exception as ex: return False13 unmodified lines14151617181920212223242526272829303132331 unmodified line35363738394018 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210313 unmodified lines11711811912012112212312412512612749 unmodified lines177178179180181182183184185186187121 unmodified lines3093103113123133143153163177 unmodified lines32532632732832933013 unmodified linesfrom nemoguardrails.rails import LLMRails, RailsConfigfrom langchain.chat_models import ChatOpenAIfrom firebase_admin import storagefrom .csv_embed import get_embedfrom .llm.llms import get_llm, GPT_4, FALCON_7Bfrom .pinecone_engine import init_pineconefrom ..common.brain_exception import BrainExceptionfrom ..common.http_response_codes import responsesfrom ..common.utils import (OPENAI_API_KEY,FIREBASE_STORAGE_ROOT,DEFAULT_GPT_MODEL,parseJsonFromCompletion,PINECONE_INDEX_NAME,)from .image_embedding import (query_image_text,1 unmodified line)from ..model.req_model import ReqModelfrom ..model.requests.request_model import BasicReqfrom ..service.train_service import TrainService# Give the path to the folder containing the rails18 unmodified linesimage_search: bool = True,is_browser: bool = False,) -> Any:"""step 0: convert string to json"""index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)train_service = TrainService(firebase_app=firebase_app, setting=setting)"""step 1: handle with gpt-4"""query_result = get_embed(data=query, setting=setting)try:relatedness_data = index.query(vector=query_result,top_k=1,include_values=False,namespace=train_service.get_pinecone_index_train_namespace(),)except Exception as ex:raise BrainException(code=508, message=responses[508])if len(relatedness_data["matches"]) == 0:return str({"program": "message", "content": ""})document_id = relatedness_data["matches"][0]["id"]document = train_service.read_one_document(document_id)page_content = document["page_content"]message = rails_app.generate(messages=[{"role": "user","content": rails_input_with_args(setting=setting,query=query,image_search=image_search,page_content=page_content,document_id=document_id,is_browser=is_browser,),}])return messagedef processLargeText(13 unmodified linesimage_search=image_search,is_browser=is_browser,)try:return json.loads(message["content"])except Exception as e:result = json.dumps(message["content"])return parseJsonFromCompletion(result)else:first_query = "The total length of the content that I want to send you is too large to send in only one piece.\nFor sending you that content, I will follow this rule:\n[START PART 1/10]\nThis is the content of the part 1 out of 10 in total\n[END PART 1/10]\nThen you just answer: 'Received part 1/10'\nAnd when I tell you 'ALL PART SENT', then you can continue processing the data and answering my requests."app.generate(messages=[{"role": "user", "content": first_query}])49 unmodified linesimage_search=image_search,is_browser=is_browser,)try:return json.loads(message["content"])except Exception as e:result = json.dumps(message["content"])return parseJsonFromCompletion(result)# out of for-loop121 unmodified linessetting: ReqModel,query: str,image_search: bool,page_content: str,document_id: str,is_browser: bool,) -> str:# convert json with params for rails.json_query_with_params = {7 unmodified linesreturn json.dumps(json_query_with_params)def handle_chat_completion(messages: Any, model: str = "gpt-3.5-turbo") -> Any:openai.api_key = OPENAI_API_KEY13 unmodified lines14151617181920212223242526272829303132333435363738391 unmodified line4142434445464718 unmodified lines6667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912013 unmodified lines13413513613713813914049 unmodified lines190191192193194195196121 unmodified lines3183193203213223233243253267 unmodified lines33433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139213 unmodified linesfrom nemoguardrails.rails import LLMRails, RailsConfigfrom langchain.chat_models import ChatOpenAIfrom langchain.docstore.document import Documentfrom firebase_admin import storagefrom .csv_embed import get_embedfrom .llm.falcon_llm import FalconLLMfrom .llm.llms import get_llm, GPT_4, FALCON_7B, get_llm_chain, CATEGORY_PROMPTfrom .pinecone_engine import init_pineconefrom .rails_validate import validate_railsfrom ..common.brain_exception import BrainExceptionfrom ..common.http_response_codes import responsesfrom ..common.program_type import ProgramTypefrom ..common.utils import (OPENAI_API_KEY,FIREBASE_STORAGE_ROOT,DEFAULT_GPT_MODEL,parseJsonFromCompletion,PINECONE_INDEX_NAME,ACTION_FLAG,COMMAND_SMS_INDEXES,COMMAND_BROWSER_OPEN,)from .image_embedding import (query_image_text,1 unmodified line)from ..model.req_model import ReqModelfrom ..model.requests.request_model import BasicReqfrom ..service.auto_task_service import AutoTaskServicefrom ..service.train_service import TrainService# Give the path to the folder containing the rails18 unmodified linesimage_search: bool = True,is_browser: bool = False,) -> Any:# rails validationrails_resp = rails_app.generate(messages=[{"role": "user","content": query,}])if not validate_rails(rails_resp):json_resp = json.loads(rails_resp["content"])json_resp["program"] = ProgramType.MESSAGEreturn json_resp# queryingdocument_id = ""page_content = ""if not ACTION_FLAG:"""step 0: convert string to json"""index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)train_service = TrainService(firebase_app=firebase_app, setting=setting)"""step 1: handle with gpt-4"""query_result = get_embed(data=query, setting=setting)try:relatedness_data = index.query(vector=query_result,top_k=1,include_values=False,namespace=train_service.get_pinecone_index_train_namespace(),)except Exception as ex:raise BrainException(code=508, message=responses[508])if len(relatedness_data["matches"]) == 0:return str({"program": "message", "content": ""})document_id = relatedness_data["matches"][0]["id"]document = train_service.read_one_document(document_id)page_content = document["page_content"]return ask_question(query=query,setting=setting,is_browser=is_browser,image_search=image_search,document_id=document_id,page_content=page_content,)def processLargeText(13 unmodified linesimage_search=image_search,is_browser=is_browser,)return messageelse:first_query = "The total length of the content that I want to send you is too large to send in only one piece.\nFor sending you that content, I will follow this rule:\n[START PART 1/10]\nThis is the content of the part 1 out of 10 in total\n[END PART 1/10]\nThen you just answer: 'Received part 1/10'\nAnd when I tell you 'ALL PART SENT', then you can continue processing the data and answering my requests."app.generate(messages=[{"role": "user", "content": first_query}])49 unmodified linesimage_search=image_search,is_browser=is_browser,)return message# out of for-loop121 unmodified linessetting: ReqModel,query: str,image_search: bool,is_browser: bool,page_content: str = "",document_id: str = "",) -> str:# convert json with params for rails.json_query_with_params = {7 unmodified linesreturn json.dumps(json_query_with_params)"""main method to handle basic query"""def ask_question(query: str,setting: ReqModel,is_browser: bool,image_search: bool,document_id: str = "",page_content: str = "",) -> Any:"""init falcon model"""falcon_llm = FalconLLM()autotask_service = AutoTaskService()docs = []if ACTION_FLAG:docs.append(Document(page_content=CATEGORY_PROMPT, metadata=""))# temperature shouldbe 0.chain_data = get_llm_chain(model=DEFAULT_GPT_MODEL, setting=setting, temperature=0.0).run(input_documents=docs, question=query)else:docs.append(Document(page_content=page_content, metadata=""))""" 1. calling gpt model to categorize for all message"""chain_data = get_llm_chain(model=DEFAULT_GPT_MODEL, setting=setting).run(input_documents=docs, question=query)try:result = json.loads(chain_data)# check image query with only its textif result["program"] == ProgramType.IMAGE:if image_search:result["content"] = {"image_name": query_image_text(result["content"], "", setting)}""" 2. check program is message to handle it with falcon llm """if result["program"] == ProgramType.MESSAGE:if is_browser:result["program"] = ProgramType.BrowserType.ASK_WEBSITEreturn resultexcept ValueError as e:# Check sms and browser queryif document_id in COMMAND_SMS_INDEXES:return {"program": ProgramType.SMS, "content": chain_data}elif document_id in COMMAND_BROWSER_OPEN:return {"program": ProgramType.BROWSER, "content": "https://google.com"}if is_browser:return {"program": ProgramType.BrowserType.ASK_WEBSITE, "content": ""}return {"program": ProgramType.MESSAGE, "content": chain_data}def handle_chat_completion(messages: Any, model: str = "gpt-3.5-turbo") -> Any:openai.api_key = OPENAI_API_KEY
17 unmodified lines1819202122236 unmodified lines303132333435363738394046 unmodified lines87888990919293309 unmodified lines40340440540640740840924 unmodified lines4344354364374384394403 unmodified lines44444544644717 unmodified linesBasicReq,ClientInfo,get_client_info,)from Brain.src.rising_plugin.risingplugin import (getCompletion,6 unmodified linesfrom Brain.src.logs import loggerfrom Brain.src.model.basic_model import BasicModelfrom Brain.src.model.feedback_model import FeedbackModelfrom Brain.src.service.command_service import CommandServicefrom Brain.src.service.contact_service import ContactsServicefrom Brain.src.service.feedback_service import FeedbackServicefrom Brain.src.service.llm.chat_service import ChatServicefrom Brain.src.service.twilio_service import TwilioServicefrom fastapi import APIRouter, Depends46 unmodified lines# check contact queryingtry:contacts_service = ContactsService(setting=setting)if result["program"] == ProgramType.CONTACT:# querying contacts to getting its expected resultscontacts_results = contacts_service.query_contacts(309 unmodified linesfor contact in data.contacts:contacts.append(assembler.to_contact_model(contact))# train contactcontacts_service = ContactsService(setting=setting)contacts_service.train(uuid, contacts)except Exception as e:if isinstance(e, BrainException):24 unmodified lines# parsing contacts# train contactcontacts_service = ContactsService(setting=setting)contacts_service.delete_all(uuid)except Exception as e:if isinstance(e, BrainException):3 unmodified lines200, "Deleted all contacts from pinecone successfully", "")return router17 unmodified lines1819202122232425266 unmodified lines3334353637383940414243444546 unmodified lines9293949596979899100101102103104105106107309 unmodified lines41741841942042142242342442524 unmodified lines4504514524534544554564574583 unmodified lines46246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453517 unmodified linesBasicReq,ClientInfo,get_client_info,AutoTaskDelete,EmailReader,GetContactsByIds,)from Brain.src.rising_plugin.risingplugin import (getCompletion,6 unmodified linesfrom Brain.src.logs import loggerfrom Brain.src.model.basic_model import BasicModelfrom Brain.src.model.feedback_model import FeedbackModelfrom Brain.src.service.auto_task_service import AutoTaskServicefrom Brain.src.service.command_service import CommandServicefrom Brain.src.service.contact_service import ContactsServicefrom Brain.src.service.feedback_service import FeedbackServicefrom Brain.src.service.llm.chat_service import ChatServicefrom Brain.src.service.twilio_service import TwilioServicefrom Brain.src.service.auto_task_service import delete_db_datafrom fastapi import APIRouter, Depends46 unmodified lines# check contact queryingtry:contacts_service = ContactsService(firebase_app=firebase_app, setting=setting)if result["program"] == ProgramType.AUTO_TASK:auto_task_service = AutoTaskService()result["content"] = auto_task_service.ask_task_with_autogpt(query=query, firebase_app=firebase_app, setting=setting)return assembler.to_response(200, "", result)if result["program"] == ProgramType.CONTACT:# querying contacts to getting its expected resultscontacts_results = contacts_service.query_contacts(309 unmodified linesfor contact in data.contacts:contacts.append(assembler.to_contact_model(contact))# train contactcontacts_service = ContactsService(firebase_app=firebase_app, setting=setting)contacts_service.train(uuid, contacts)except Exception as e:if isinstance(e, BrainException):24 unmodified lines# parsing contacts# train contactcontacts_service = ContactsService(firebase_app=firebase_app, setting=setting)contacts_service.delete_all(uuid)except Exception as e:if isinstance(e, BrainException):3 unmodified lines200, "Deleted all contacts from pinecone successfully", "")"""@generator.request_body({"token": "String","uuid": "String","data": {"reference_link": "test link",},})@generator.response(status_code=200, schema={"message": "message", "result": "test_result"})"""@router.post("/auto_task/delete")def delete_data(data: AutoTaskDelete):# firebase admin inittry:setting, firebase_app = firebase_admin_with_setting(data)except BrainException as ex:return assembler.to_response(ex.code, ex.message, "")try:token = setting.tokenuuid = setting.uuid# parsing contacts# train contactdelete_db_data(data.data.reference_link, firebase_app)except Exception as e:if isinstance(e, BrainException):return e.get_response_exp()return assembler.to_response(400, "Failed to delete data", "")return assembler.to_response(200, "Deleted data from real-time database of firebase", "")"""@generator.request_body({"token": "String","uuid": "String","contactIds": ["String"]})@generator.response(status_code=200, schema={"message": "message", "result": "test_result"})"""@router.post("/contacts/get_by_ids")def get_contacts_by_ids(data: GetContactsByIds):try:setting, firebase_app = firebase_admin_with_setting(data)except BrainException as ex:return ex.get_response_exp()token: str = setting.tokenuuid: str = setting.uuidresult = ContactsService(firebase_app=firebase_app, setting=setting).get_contacts_by_ids(uuid=uuid, contactIds=data.contactIds)return assembler.to_response(200, "Success to get contacts by uuid", result)return router
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import json
from fastapi import APIRouter
from Brain.src.common.assembler import Assemblerfrom Brain.src.common.brain_exception import BrainExceptionfrom Brain.src.model.requests.request_model import ( EmailReader,)from Brain.src.rising_plugin.gmail.email_plugin import EmailPluginfrom Brain.src.firebase.firebase import firebase_admin_with_setting
router = APIRouter()
def construct_blueprint_email_api() -> APIRouter: # Assembler assembler = Assembler() # Services
"""@generator.request_body( { "token": "String", "uuid": "String", "data": { "sender": "test@gmail.com", "pwd": "use app password of your google account", "imap_folder": "inbox or drafts" }, } )
@generator.response( status_code=200, schema={"message": "message", "result": [{ "From": "testfrom@test.com", "To": "test@gmail.com", "Date": "Tue, 04 Jul 2023 12:55:19 +0000", "CC": "", "Subject": "subject", "Message Body": "message" }]} )
"""
@router.post("/read_emails") def read_emails(data: EmailReader): # firebase admin init try: setting, firebase_app = firebase_admin_with_setting(data) except BrainException as ex: return assembler.to_response(ex.code, ex.message, "") try: token = setting.token uuid = setting.uuid
# if imap_folder is drafts, then search is ALL imap_search_cmd = "UNSEEN" if data.data.imap_folder not in "inbox": imap_search_cmd = "(ALL)"
# read emails email_manager = EmailPlugin() result = email_manager.read_emails( sender=data.data.sender, pwd=data.data.pwd, imap_folder=data.data.imap_folder, imap_search_command=imap_search_cmd, ) result = json.loads(result) except Exception as e: if isinstance(e, BrainException): return e.get_response_exp() return assembler.to_response(400, "Failed to read emails", "") return assembler.to_response(200, "", result)
return router156 unmodified lines157158159160156 unmodified lines200, "deleted one document and train data successfully", result)return router156 unmodified lines157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187156 unmodified lines200, "deleted one document and train data successfully", result)"""@generator.request_body({"token": "test_token","uuid": "test_uuid",})@generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id"}} )"""@router.post("/delete/all/vectors")def delete_all_pinecone(data: BasicReq):# parsing paramstry:setting, firebase_app = firebase_admin_with_setting(data)except BrainException as ex:return ex.get_response_exp()# Servicestrain_service = TrainService(firebase_app=firebase_app, setting=setting)try:result = train_service.delete_all_training_from_pinecone()except Exception as e:if isinstance(e, BrainException):return e.get_response_exp()return assembler.to_response(400, "fail to delete one train", "")return assembler.to_response(200, "deleted one document and train data successfully", result)return router
12345678911 unmodified lines212223242526272829"""auto task management to get the expected output"""import firebase_adminfrom Brain.src.model.req_model import ReqModelfrom Brain.src.rising_plugin.llm.autogpt_llm import AutoGPTLLMimport timeclass AutoTaskService:11 unmodified linesllm_name="autogpt", uuid=setting.uuid)# call autogptautogpt_llm.ask_task(query=query, firebase_app=firebase_app, reference_link=reference_link)return reference_link123456789101112131415161718192011 unmodified lines32333435363738394041"""auto task management to get the expected output"""import firebase_adminfrom firebase_admin import dbfrom Brain.src.model.req_model import ReqModelfrom Brain.src.rising_plugin.llm.autogpt_llm import AutoGPTLLMimport timeimport asyncioimport threading"""delete data from real time database of firebase using reference link"""def delete_db_data(reference_link: str, firebase_app: firebase_admin.App):ref = db.reference(reference_link, app=firebase_app)ref.delete()class AutoTaskService:11 unmodified linesllm_name="autogpt", uuid=setting.uuid)# call autogptthread = threading.Thread(target=autogpt_llm.ask_task, args=(query, firebase_app, reference_link))thread.start()return reference_link
1234568 unmodified lines151617181920212223243 unmodified lines282930313233347 unmodified lines4243444546474849505152531 unmodified line55565758596024 unmodified lines858687"""service to manage contacts"""from typing import List, Anyfrom Brain.src.model.req_model import ReqModelfrom Brain.src.rising_plugin.csv_embed import get_embedfrom Brain.src.rising_plugin.pinecone_engine import (8 unmodified linesfrom Brain.src.common.utils import PINECONE_INDEX_NAMEfrom Brain.src.model.contact_model import ContactModel, ContactStatusclass ContactsService:def __init__(self, setting: ReqModel):self.setting = setting"""train contacts (getting embedding) and update pinecone with embeddings by contact_idtrain datatype:3 unmodified linesdef train(self, uuid: str, contacts: List[ContactModel]) -> None:# getting index namespaceof pineconepinecone_namespace = self.get_pinecone_index_namespace(uuid)for contact in contacts:# generate key and values for pinecone datakey = contact.contact_idvalue = f"{contact.display_name}, {contact.get_str_phones()}"7 unmodified linesvalue=vectoring_values,setting=self.setting,)elif contact.status == ContactStatus.DELETED:delete_pinecone(namespace=pinecone_namespace,key=key,setting=self.setting,)elif contact.status == ContactStatus.UPDATED:update_pinecone(namespace=pinecone_namespace,1 unmodified linevalue=vectoring_values,setting=self.setting,)""""query contact with search textresponse: list of contactId as index key of pinecone"""24 unmodified linesdef get_pinecone_index_namespace(self, uuid: str) -> str:return get_pinecone_index_namespace(f"{uuid}-contacts")123456788 unmodified lines1718192021222324252627282930313233343 unmodified lines3839404142434445467 unmodified lines54555657585960616263646566671 unmodified line6970717273747524 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""service to manage contacts"""from typing import List, Anyfrom Brain.src.common.assembler import Assemblerfrom Brain.src.model.req_model import ReqModelfrom Brain.src.rising_plugin.csv_embed import get_embedfrom Brain.src.rising_plugin.pinecone_engine import (8 unmodified linesfrom Brain.src.common.utils import PINECONE_INDEX_NAMEfrom Brain.src.model.contact_model import ContactModel, ContactStatusimport firebase_adminfrom firebase_admin import firestoreclass ContactsService:db: Anyphones_ref: Anydef __init__(self, firebase_app: firebase_admin.App, setting: ReqModel):self.firebase_app = firebase_appself.setting = settingself.init_firestore()"""train contacts (getting embedding) and update pinecone with embeddings by contact_idtrain datatype:3 unmodified linesdef train(self, uuid: str, contacts: List[ContactModel]) -> None:# getting index namespaceof pineconepinecone_namespace = self.get_pinecone_index_namespace(uuid)for contact in contacts:# Save the data# generate key and values for pinecone datakey = contact.contact_idvalue = f"{contact.display_name}, {contact.get_str_phones()}"7 unmodified linesvalue=vectoring_values,setting=self.setting,)self.create_one_contact(uuid=uuid, contact=contact)elif contact.status == ContactStatus.DELETED:delete_pinecone(namespace=pinecone_namespace,key=key,setting=self.setting,)self.delete_one_contact(uuid=uuid, contact=contact)elif contact.status == ContactStatus.UPDATED:update_pinecone(namespace=pinecone_namespace,1 unmodified linevalue=vectoring_values,setting=self.setting,)self.update_one_contact(uuid=uuid, contact=contact)""""query contact with search textresponse: list of contactId as index key of pinecone"""24 unmodified linesdef get_pinecone_index_namespace(self, uuid: str) -> str:return get_pinecone_index_namespace(f"{uuid}-contacts")"""init firestore to save user's contacts"""def init_firestore(self):self.db = firestore.client(app=self.firebase_app)self.phones_ref = self.db.collection("phones")"""create a contact into document which name is uuid in phone collections in firestore"""def create_one_contact(self, uuid: str, contact: ContactModel):assembler = Assembler()data = assembler.to_contact_result_format(contact)phones_doc_ref = self.phones_ref.document(uuid)contacts_doc_ref = phones_doc_ref.collection("contacts").document(contact.contact_id)contacts_doc_ref.set(data)"""update a contact into document which name is uuid in phone collections in firestore"""def update_one_contact(self, uuid: str, contact: ContactModel):assembler = Assembler()data = assembler.to_contact_result_format(contact)phones_doc_ref = self.phones_ref.document(uuid)contacts_doc_ref = phones_doc_ref.collection("contacts").document(contact.contact_id)contacts_doc_ref.update(data)"""delete a contact into document which name is uuid in phone collections in firestore"""def delete_one_contact(self, uuid: str, contact: ContactModel):phones_doc_ref = self.phones_ref.document(uuid)contacts_doc_ref = phones_doc_ref.collection("contacts").document(contact.contact_id)contacts_doc_ref.delete()def get_contacts_by_ids(self, uuid: str, contactIds: list[str]) -> []:phones_doc_ref = self.phones_ref.document(uuid)contacts_ref = phones_doc_ref.collection("contacts")# Retrieve all documents in the 'contacts' sub-collectioncontacts = contacts_ref.where("contactId", "in", contactIds).stream()result = []# Iterate through the documents and print out their datafor contact in contacts:result.append(contact.to_dict())return result
147 unmodified lines148149150151152153147 unmodified linessetting=self.setting,)def get_pinecone_index_namespace(self) -> str:self.init_firestore()return get_pinecone_index_namespace(f"trains")147 unmodified lines148149150151152153154155156157158159147 unmodified linessetting=self.setting,)def delete_all_training_from_pinecone(self) -> Any:self.init_firestore()return delete_all_pinecone(namespace=self.get_pinecone_index_namespace(), setting=self.setting)def get_pinecone_index_namespace(self) -> str:self.init_firestore()return get_pinecone_index_namespace(f"trains")
208 unmodified lines209210211208 unmodified linesdef test_train_contacts(body):response = client.post("/train/contacts", json=body)assert response.status_code == 200208 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237208 unmodified linesdef test_train_contacts(body):response = client.post("/train/contacts", json=body)assert response.status_code == 200@pytest.mark.parametrize("body",[({"data": {"reference_link": "test link",},"confs": {"token": "test_token","uuid": "test-uuid","openai_key": "","pinecone_key": "","pinecone_env": "","firebase_key": "","settings": {"temperature": 0.6},},})],)def test_delete_data(body):response = client.post("/auto_task/delete", json=body)assert response.status_code == 200
12345# Default ignored files/shelf//workspace.xml# Editor-based HTTP Client requests/httpRequests/123456789101112<?xml version="1.0" encoding="UTF-8"?><module type="WEB_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/.tmp" /> <excludeFolder url="file://$MODULE_DIR$/temp" /> <excludeFolder url="file://$MODULE_DIR$/tmp" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component></module>123456<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> <inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" /> </profile></component>12345678<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/Extension.iml" filepath="$PROJECT_DIR$/.idea/Extension.iml" /> </modules> </component></project>123456<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$/.." vcs="Git" /> </component></project>60 unmodified lines61626364656660 unmodified linescursor: 'move',right: 0, // Add this propertybottom: 0, // Add this property}}><Panel />60 unmodified lines616263646566676860 unmodified linescursor: 'move',right: 0, // Add this propertybottom: 0, // Add this propertywidth: '400px',height: '350px'}}><Panel />
1233 unmodified lines7891011121314151617181920212223242526.message {display: flex;flex-direction: column;3 unmodified lines.message_sent {width: fit-content;padding: 5px;border: #04c4f8 1px solid;border-radius: 3px;background-color: transparent;color: #04c4f8;align-self: end;}.message_received {width: fit-content;padding: 5px;border: #bc0fdb 1px solid;border-radius: 3px;background-color: transparent;color: #bc0fdb;}123456789101112133 unmodified lines17181920212223242526272829303132[data-theme='light'] {--send-theme-color: #0a164d;--receive-theme-color: #0d0c0d;}[data-theme='dark'] {--send-theme-color: #0a164d;--receive-theme-color: #333333;}.message {display: flex;flex-direction: column;3 unmodified lines.message_sent {width: fit-content;padding: 5px;border-radius: 5px;background-color: var(--send-theme-color);align-self: end;}.message_received {width: fit-content;padding: 5px;border-radius: 5px;background-color: var(--receive-theme-color);}
123456789108 unmodified lines19202122232419 unmodified lines44454647.main-layout {display: flex;flex-direction: column;height: 350px; /* Set the height of the layout to be 100% of the viewport */width: 400px;border-radius: 5px;background-color: #f5f5f5dd;}.main-layout .ant-layout-content {8 unmodified lines.footer {padding: 10px;justify-self: end;}.content {19 unmodified lines.divider {margin: 0;}1234567891011121314151617181920218 unmodified lines3031323334353619 unmodified lines5657585960[data-theme='light'] {--font-color: #c9d1d9;--theme-color: #333333;}[data-theme='dark'] {--font-color: #aeafb2;--theme-color: #0d0c0d;}.main-layout {display: flex;flex-direction: column;height: 350px; /* Set the height of the layout to be 100% of the viewport */width: 400px;border-radius: 10px;background-color: var(--theme-color);color: var(--font-color);}.main-layout .ant-layout-content {8 unmodified lines.footer {padding: 10px;justify-self: end;background-color: var(--theme-color);}.content {19 unmodified lines.divider {margin: 0;background-color: grey;}
111 unmodified lines1121131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816961 unmodified lines231232233234235236237238111 unmodified linesaddMessage(data.result.content, false)window.location.assign(data.result.content)breakcase 'open_tab':addMessage("open tab", false)window.open('https://google.com/search?q=', '_blank', 'noreferrer')breakcase 'open_tab_search':addMessage("open tab and search", false)window.open('https://google.com/search?q=' + data.result.content, '_blank', 'noreferrer')breakcase 'close_tab':addMessage("close tab", false)window.close()breakcase 'previous_page':if (page === 0) {page = 0} else {3 unmodified linesaddMessage("go to previous page", false)window.location.assign(currentUrl + '&start=' + page)breakcase 'next_page':page += 10addMessage("go to next page", false)window.location.assign(currentUrl + '&start=' + page)breakcase 'scroll_up':addMessage("scroll up", false)window.scrollBy(0, -300)breakcase 'scroll_down':addMessage("scroll down", false)window.scrollBy(0, 300)breakcase 'scroll_top':addMessage("scroll to top", false)window.scrollTo(0, 0)breakcase 'scroll_bottom':addMessage("scroll to bottom", false)window.scrollTo(0, document.body.scrollHeight)breakcase 'message':addMessage(data.result.content, false)breakcase 'select_item_detail_info':addMessage("I need more detail info to select item", false)selectItem()breakcase 'ask_website':askAboutCurrentWebsite()breakdefault:61 unmodified linesreturn data}return (<Layout className="main-layout"><div className="header"><h4>RisingBrowser</h4></div>111 unmodified lines1121131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816961 unmodified lines231232233234235236237238239240241242243244245246247248249250111 unmodified linesaddMessage(data.result.content, false)window.location.assign(data.result.content)breakcase 'opentab':addMessage("open tab", false)window.open('https://google.com/search?q=', '_blank', 'noreferrer')breakcase 'opentabsearch':addMessage("open tab and search", false)window.open('https://google.com/search?q=' + data.result.content, '_blank', 'noreferrer')breakcase 'closetab':addMessage("close tab", false)window.close()breakcase 'previouspage':if (page === 0) {page = 0} else {3 unmodified linesaddMessage("go to previous page", false)window.location.assign(currentUrl + '&start=' + page)breakcase 'nextpage':page += 10addMessage("go to next page", false)window.location.assign(currentUrl + '&start=' + page)breakcase 'scrollup':addMessage("scroll up", false)window.scrollBy(0, -300)breakcase 'scrolldown':addMessage("scroll down", false)window.scrollBy(0, 300)breakcase 'scrolltop':addMessage("scroll to top", false)window.scrollTo(0, 0)breakcase 'scrollbottom':addMessage("scroll to bottom", false)window.scrollTo(0, document.body.scrollHeight)breakcase 'message':addMessage(data.result.content, false)breakcase 'selectitemdetailinfo':addMessage("I need more detail info to select item", false)selectItem()breakcase 'askwebsite':askAboutCurrentWebsite()breakdefault:61 unmodified linesreturn data}/// Check if the user's system is in dark modeconst darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');const isDarkMode = darkModeMediaQuery.matches;const handleThemeChange = (e) => {const isDarkMode = e.matches;// Do something based on the new theme data};// Listen for changes in the theme datadarkModeMediaQuery.addEventListener('change', handleThemeChange);return (<Layout className="main-layout" data-theme={isDarkMode ? 'dark': 'light'}><div className="header"><h4>RisingBrowser</h4></div>
27 unmodified lines282930313233344 unmodified lines3940414243444546474827 unmodified lines- 🔗 Multiple API support (Web API for Free and Plus users, GPT-3.5, GPT-4, etc.).- 🔍 Integration to all mainstream search engines, and custom queries to support additional sites.[[Android Application](https://github.com/ttt246/RisingPhone)] [[Brrowser Extension](https://github.com/ttt246/Rising_Browser)] [[Rising Plugin](https://github.com/ttt246/Rising_Plugin)]#### 1.2 Feature- Chat with Rising AI as an assistant.4 unmodified lines- Manipulate all browsers with user's input(tab, page, search, scroll, or etc) and it will follow you to go on the real website or blog what you are thinking of.## 2. Installing / Getting startedInstall the latest version of rising-plugin package to use / custom something on what you want.```pip install rising-plugin```#### 2.1 how to run on localIt's a standard fastapi application so no configuration is needed beyond the included Procfile#### 2.2 Create firebase project27 unmodified lines282930313233344 unmodified lines39404142434427 unmodified lines- 🔗 Multiple API support (Web API for Free and Plus users, GPT-3.5, GPT-4, etc.).- 🔍 Integration to all mainstream search engines, and custom queries to support additional sites.[[Brain](https://github.com/ttt246/Brain)] [[Android Application](https://github.com/ttt246/Brain/tree/main/Android)] [[Brrowser Extension](https://github.com/ttt246/Brain/tree/main/Extension)] [[Apple Watch](https://github.com/ttt246/Brain/tree/main/WatchApp)]#### 1.2 Feature- Chat with Rising AI as an assistant.4 unmodified lines- Manipulate all browsers with user's input(tab, page, search, scroll, or etc) and it will follow you to go on the real website or blog what you are thinking of.## 2. Installing / Getting started#### 2.1 how to run on localIt's a standard fastapi application so no configuration is needed beyond the included Procfile#### 2.2 Create firebase project
1234567891011{ "colors" : [ { "idiom" : "universal" } ], "info" : { "author" : "xcode", "version" : 1 }}12345678910111213{ "images" : [ { "idiom" : "universal", "platform" : "watchos", "size" : "1024x1024" } ], "info" : { "author" : "xcode", "version" : 1 }}123456{ "info" : { "author" : "xcode", "version" : 1 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657//// MessageView.swift// WatchApp Watch App//// Created by DarkHorse on 7/1/23.//
import SwiftUI
struct ChatMessage: Hashable { let message: String let isUser: Bool}
struct ChatBubble: Shape { let isUser: Bool
func path(in rect: CGRect) -> Path { let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight, isUser ? .bottomLeft : .bottomRight], cornerRadii: CGSize(width: 3, height: 3)) return Path(path.cgPath) }}
struct ChatMessageRow: View { let message: ChatMessage
var body: some View { HStack { if message.isUser { Spacer() Text(message.message) .font(.system(size: 15)) .foregroundColor(.white) .padding(5) .background(Color.blue) .clipShape(ChatBubble(isUser: message.isUser)) } else { Text(message.message) .italic() .font(.system(size: 15)) .foregroundColor(.black) .padding(5) .background(Color.primary) .clipShape(ChatBubble(isUser: message.isUser)) Spacer() } }.listRowBackground(Color.clear) }}
struct ChatMessageRow_Previews: PreviewProvider { static var previews: some View { ChatMessageRow(message: ChatMessage(message: "Hello!", isUser: false)) }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273//// ContentView.swift// WatchApp Watch App//// Created by DarkHorse on 6/28/23.//
import SwiftUI
struct ChatMessage: Hashable { let message: String let isUser: Bool}
struct ChatBubble: Shape { let isUser: Bool
func path(in rect: CGRect) -> Path { let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight, isUser ? .bottomLeft : .bottomRight], cornerRadii: CGSize(width: 10, height: 10)) return Path(path.cgPath) }}
struct ContentView: View { @State private var messages: [ChatMessage] = [] @State private var newMessage = "" var body: some View { VStack { List { ForEach(messages, id: \.self) { message in HStack { if message.isUser { Spacer() Text(message.message) .foregroundColor(.white) .padding(10) .background(Color.blue) .clipShape(ChatBubble(isUser: message.isUser)) } else { Text(message.message) .foregroundColor(.white) .padding(10) .background(Color.gray) .clipShape(ChatBubble(isUser: message.isUser)) Spacer() } } } } HStack { TextField("Message...", text: $newMessage) Button(action: { let userMessage = ChatMessage(message: newMessage, isUser: true) messages.append(userMessage) newMessage = "" }) { Text("Send") } } .padding() } }}
struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() }}12345678910111213141516171819202122232425262728//// MainView.swift// WatchApp Watch App//// Created by DarkHorse on 7/1/23.//
import SwiftUI
struct MainView: View { @State private var isPresented = false var body: some View { ZStack { if isPresented { SettingView(isPresented: $isPresented) } else { ChatView(isPresented: $isPresented) } } }}
struct MainView_Previews: PreviewProvider { static var previews: some View { MainView() }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112//// ContentView.swift// WatchApp Watch App//// Created by Hideki Sato on 6/27/23.//
import SwiftUIimport KeychainSwift
struct ChatView: View { @Binding var isPresented: Bool @State private var messages: [ChatMessage] = [] @State private var newMessage = "" @State private var uuid: String = "956a11be45cba4a4" var body: some View { VStack{ Button(action: { self.isPresented = true }) { Image(systemName: "gearshape.fill") .resizable() .frame(width: 15, height: 15) } .frame(width: 50, height: 30) .background(Color.clear).buttonStyle(PlainButtonStyle()).padding(.trailing) List { ForEach(messages, id: \.self) { message in ChatMessageRow(message:message) } }.listStyle(PlainListStyle()).padding(.bottom, 10) HStack() { TextField("Message...", text: $newMessage).frame(width: 120.0, height: 0) Button(action: { let keychain = KeychainSwift()
// Try to get the UUID from the keychain if keychain.get("uuid") == "" { let uuid = "956a11be45cba4a4" keychain.set(uuid, forKey: "uuid") } let userMessage = ChatMessage(message: newMessage, isUser: true) messages.append(userMessage) // Replace this URL with your server's URL if let url = URL(string: "https://ttt246-brain.hf.space/sendNotification") { var request = URLRequest(url: url) request.httpMethod = "POST" // Change this to any HTTP method you want request.addValue("application/json", forHTTPHeaderField: "Content-Type") // Add any necessary headers let confsData: [String: Any] = [ "openai_key": "", "pinecone_key": "", "pinecone_env": "", "firebase_key": "", "token":"cI3EvimJQv-G5imdWrBprf:APA91bEZ5u6uq9Yq4a6NglN0L9pVM7p-rlxKB_FikbfKlzHnZT5GeAjxF0deuPT2GurS8bK6JTE2XPZLQqbsrtjxeRGhGOH5INoQ7MrRlr4TR3xFswKxJSkfi1aBUWDaLGALeirZ7GuZ", "uuid": uuid, "settings": [ "temperature": 0.6 ] ] let postData: [String: Any] = ["confs": confsData, "message": newMessage] do { let jsonData = try JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted) URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in guard error == nil, let data = data else { print("Error: \(error?.localizedDescription ?? "Unknown error")") return } do { // Here we are converting data into JSON using JSONSerialization if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { if let result = jsonResult["result"] as? [String: Any], let content = result["content"] as? String { DispatchQueue.main.async { let serverResponse = ChatMessage(message: content, isUser: false) messages.append(serverResponse) } } } } catch { print("JSONSerialization error: \(error.localizedDescription)") } }.resume() } catch { print("Error: \(error.localizedDescription)") } } newMessage = "" }) { Image(systemName: "paperplane.fill") }.frame(width: 50.0, height: 35) } }.padding().edgesIgnoringSafeArea(.all) }}
struct ChatView_Previews: PreviewProvider { static var previews: some View { ChatView(isPresented: .constant(false)) }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546//// SettingView.swift// WatchApp Watch App//// Created by DarkHorse on 7/1/23.//
import SwiftUIimport KeychainSwift
struct SettingView: View { @Binding var isPresented: Bool @State private var uuid: String = "956a11be45cba4a4" var body: some View { VStack { TextField("uuid", text: $uuid) .foregroundColor(.white) .font(.system(size: 20)) .padding() HStack { Spacer() Button(action: { let keychain = KeychainSwift() keychain.set("\($uuid)", forKey: "uuid") self.isPresented = false }) { Text("Yes") } Spacer() Button(action: { self.isPresented = false }) { Text("No") } Spacer() } } }}
struct SettingView_Previews: PreviewProvider { static var previews: some View { SettingView(isPresented: .constant(true)) }}10 unmodified lines1112131415161710 unmodified linesstruct WatchApp_Watch_AppApp: App {var body: some Scene {WindowGroup {ContentView()}}}10 unmodified lines1112131415161710 unmodified linesstruct WatchApp_Watch_AppApp: App {var body: some Scene {WindowGroup {MainView()}}}
8 unmodified lines9101112131415161718192038 unmodified lines59606162636465666768697071721 unmodified line74757677787938 unmodified lines11811912012112212312412512612712812913013113213313413513613713813911 unmodified lines15115215315415515627 unmodified lines18418518618718818969 unmodified lines25926026126226326418 unmodified lines28328428528628728828929018 unmodified lines309310311312313314315364 unmodified lines6806816826836846858 unmodified lines/* Begin PBXBuildFile section */FE56FAE22A4C5810008410B4 /* WatchApp Watch App.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = FE56FAE12A4C5810008410B4 /* WatchApp Watch App.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };FE56FAE72A4C5810008410B4 /* WatchAppApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FAE62A4C5810008410B4 /* WatchAppApp.swift */; };FE56FAE92A4C5810008410B4 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FAE82A4C5810008410B4 /* ContentView.swift */; };FE56FAEB2A4C5814008410B4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FE56FAEA2A4C5814008410B4 /* Assets.xcassets */; };FE56FAEE2A4C5814008410B4 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FE56FAED2A4C5814008410B4 /* Preview Assets.xcassets */; };FE56FAF82A4C5814008410B4 /* WatchApp_Watch_AppTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FAF72A4C5814008410B4 /* WatchApp_Watch_AppTests.swift */; };FE56FB022A4C5814008410B4 /* WatchApp_Watch_AppUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FB012A4C5814008410B4 /* WatchApp_Watch_AppUITests.swift */; };FE56FB042A4C5814008410B4 /* WatchApp_Watch_AppUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FB032A4C5814008410B4 /* WatchApp_Watch_AppUITestsLaunchTests.swift */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */38 unmodified linesFE56FADB2A4C5810008410B4 /* WatchApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = WatchApp.app; sourceTree = BUILT_PRODUCTS_DIR; };FE56FAE12A4C5810008410B4 /* WatchApp Watch App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "WatchApp Watch App.app"; sourceTree = BUILT_PRODUCTS_DIR; };FE56FAE62A4C5810008410B4 /* WatchAppApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchAppApp.swift; sourceTree = "<group>"; };FE56FAE82A4C5810008410B4 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };FE56FAEA2A4C5814008410B4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };FE56FAED2A4C5814008410B4 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };FE56FAF32A4C5814008410B4 /* WatchApp Watch AppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "WatchApp Watch AppTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };FE56FAF72A4C5814008410B4 /* WatchApp_Watch_AppTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchApp_Watch_AppTests.swift; sourceTree = "<group>"; };FE56FAFD2A4C5814008410B4 /* WatchApp Watch AppUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "WatchApp Watch AppUITests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };FE56FB012A4C5814008410B4 /* WatchApp_Watch_AppUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchApp_Watch_AppUITests.swift; sourceTree = "<group>"; };FE56FB032A4C5814008410B4 /* WatchApp_Watch_AppUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchApp_Watch_AppUITestsLaunchTests.swift; sourceTree = "<group>"; };/* End PBXFileReference section *//* Begin PBXFrameworksBuildPhase section */1 unmodified lineisa = PBXFrameworksBuildPhase;buildActionMask = 2147483647;files = ();runOnlyForDeploymentPostprocessing = 0;};38 unmodified linesFE56FAE52A4C5810008410B4 /* WatchApp Watch App */ = {isa = PBXGroup;children = (FE56FAE62A4C5810008410B4 /* WatchAppApp.swift */,FE56FAE82A4C5810008410B4 /* ContentView.swift */,FE56FAEA2A4C5814008410B4 /* Assets.xcassets */,FE56FAEC2A4C5814008410B4 /* Preview Content */,);path = "WatchApp Watch App";sourceTree = "<group>";};FE56FAEC2A4C5814008410B4 /* Preview Content */ = {isa = PBXGroup;children = (FE56FAED2A4C5814008410B4 /* Preview Assets.xcassets */,);path = "Preview Content";sourceTree = "<group>";};FE56FAF62A4C5814008410B4 /* WatchApp Watch AppTests */ = {isa = PBXGroup;children = (11 unmodified linespath = "WatchApp Watch AppUITests";sourceTree = "<group>";};/* End PBXGroup section *//* Begin PBXNativeTarget section */27 unmodified linesdependencies = ();name = "WatchApp Watch App";productName = "WatchApp Watch App";productReference = FE56FAE12A4C5810008410B4 /* WatchApp Watch App.app */;productType = "com.apple.product-type.application";69 unmodified linesBase,);mainGroup = FE56FAD42A4C580F008410B4;productRefGroup = FE56FADC2A4C5810008410B4 /* Products */;projectDirPath = "";projectRoot = "";18 unmodified linesisa = PBXResourcesBuildPhase;buildActionMask = 2147483647;files = (FE56FAEE2A4C5814008410B4 /* Preview Assets.xcassets in Resources */,FE56FAEB2A4C5814008410B4 /* Assets.xcassets in Resources */,);runOnlyForDeploymentPostprocessing = 0;};18 unmodified linesisa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (FE56FAE92A4C5810008410B4 /* ContentView.swift in Sources */,FE56FAE72A4C5810008410B4 /* WatchAppApp.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;364 unmodified linesdefaultConfigurationName = Release;};/* End XCConfigurationList section */};rootObject = FE56FAD52A4C580F008410B4 /* Project object */;}8 unmodified lines91011121314151617181920212238 unmodified lines6162636465666768697071727374751 unmodified line7778798081828338 unmodified lines12212312412512612712812913013113213313413511 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816927 unmodified lines19719819920020120220320420569 unmodified lines27527627727827928028128228318 unmodified lines30230330430530630718 unmodified lines326327328329330331332333334335364 unmodified lines7007017027037047057067077087097107117127137147157167177187197207217227237248 unmodified lines/* Begin PBXBuildFile section */FE56FAE22A4C5810008410B4 /* WatchApp Watch App.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = FE56FAE12A4C5810008410B4 /* WatchApp Watch App.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };FE56FAE72A4C5810008410B4 /* WatchAppApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FAE62A4C5810008410B4 /* WatchAppApp.swift */; };FE56FAF82A4C5814008410B4 /* WatchApp_Watch_AppTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FAF72A4C5814008410B4 /* WatchApp_Watch_AppTests.swift */; };FE56FB022A4C5814008410B4 /* WatchApp_Watch_AppUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FB012A4C5814008410B4 /* WatchApp_Watch_AppUITests.swift */; };FE56FB042A4C5814008410B4 /* WatchApp_Watch_AppUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FB032A4C5814008410B4 /* WatchApp_Watch_AppUITestsLaunchTests.swift */; };FE56FB142A4C80A5008410B4 /* ChatView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE56FAE82A4C5810008410B4 /* ChatView.swift */; };FE673FCB2A4CDBF7003EF230 /* KeychainSwift in Frameworks */ = {isa = PBXBuildFile; productRef = FE673FCA2A4CDBF7003EF230 /* KeychainSwift */; };FE673FCE2A5022C9003EF230 /* ChatMessageRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE673FCD2A5022C9003EF230 /* ChatMessageRow.swift */; };FE673FD02A504903003EF230 /* SettingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE673FCF2A504903003EF230 /* SettingView.swift */; };FE673FD32A504EAF003EF230 /* MainView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE673FD22A504EAF003EF230 /* MainView.swift */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */38 unmodified linesFE56FADB2A4C5810008410B4 /* WatchApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = WatchApp.app; sourceTree = BUILT_PRODUCTS_DIR; };FE56FAE12A4C5810008410B4 /* WatchApp Watch App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "WatchApp Watch App.app"; sourceTree = BUILT_PRODUCTS_DIR; };FE56FAE62A4C5810008410B4 /* WatchAppApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchAppApp.swift; sourceTree = "<group>"; };FE56FAE82A4C5810008410B4 /* ChatView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatView.swift; sourceTree = "<group>"; };FE56FAF32A4C5814008410B4 /* WatchApp Watch AppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "WatchApp Watch AppTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };FE56FAF72A4C5814008410B4 /* WatchApp_Watch_AppTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchApp_Watch_AppTests.swift; sourceTree = "<group>"; };FE56FAFD2A4C5814008410B4 /* WatchApp Watch AppUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "WatchApp Watch AppUITests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };FE56FB012A4C5814008410B4 /* WatchApp_Watch_AppUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchApp_Watch_AppUITests.swift; sourceTree = "<group>"; };FE56FB032A4C5814008410B4 /* WatchApp_Watch_AppUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchApp_Watch_AppUITestsLaunchTests.swift; sourceTree = "<group>"; };FE673FCD2A5022C9003EF230 /* ChatMessageRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatMessageRow.swift; sourceTree = "<group>"; };FE673FCF2A504903003EF230 /* SettingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingView.swift; sourceTree = "<group>"; };FE673FD22A504EAF003EF230 /* MainView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainView.swift; sourceTree = "<group>"; };/* End PBXFileReference section *//* Begin PBXFrameworksBuildPhase section */1 unmodified lineisa = PBXFrameworksBuildPhase;buildActionMask = 2147483647;files = (FE673FCB2A4CDBF7003EF230 /* KeychainSwift in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};38 unmodified linesFE56FAE52A4C5810008410B4 /* WatchApp Watch App */ = {isa = PBXGroup;children = (FE673FCC2A502280003EF230 /* Components */,FE673FD12A504913003EF230 /* Pages */,FE673FD22A504EAF003EF230 /* MainView.swift */,FE56FAE62A4C5810008410B4 /* WatchAppApp.swift */,);path = "WatchApp Watch App";sourceTree = "<group>";};FE56FAF62A4C5814008410B4 /* WatchApp Watch AppTests */ = {isa = PBXGroup;children = (11 unmodified linespath = "WatchApp Watch AppUITests";sourceTree = "<group>";};FE673FCC2A502280003EF230 /* Components */ = {isa = PBXGroup;children = (FE673FCD2A5022C9003EF230 /* ChatMessageRow.swift */,);path = Components;sourceTree = "<group>";};FE673FD12A504913003EF230 /* Pages */ = {isa = PBXGroup;children = (FE673FCF2A504903003EF230 /* SettingView.swift */,FE56FAE82A4C5810008410B4 /* ChatView.swift */,);path = Pages;sourceTree = "<group>";};/* End PBXGroup section *//* Begin PBXNativeTarget section */27 unmodified linesdependencies = ();name = "WatchApp Watch App";packageProductDependencies = (FE673FCA2A4CDBF7003EF230 /* KeychainSwift */,);productName = "WatchApp Watch App";productReference = FE56FAE12A4C5810008410B4 /* WatchApp Watch App.app */;productType = "com.apple.product-type.application";69 unmodified linesBase,);mainGroup = FE56FAD42A4C580F008410B4;packageReferences = (FE673FC92A4CDBF7003EF230 /* XCRemoteSwiftPackageReference "keychain-swift" */,);productRefGroup = FE56FADC2A4C5810008410B4 /* Products */;projectDirPath = "";projectRoot = "";18 unmodified linesisa = PBXResourcesBuildPhase;buildActionMask = 2147483647;files = ();runOnlyForDeploymentPostprocessing = 0;};18 unmodified linesisa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (FE673FCE2A5022C9003EF230 /* ChatMessageRow.swift in Sources */,FE673FD02A504903003EF230 /* SettingView.swift in Sources */,FE56FB142A4C80A5008410B4 /* ChatView.swift in Sources */,FE673FD32A504EAF003EF230 /* MainView.swift in Sources */,FE56FAE72A4C5810008410B4 /* WatchAppApp.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;364 unmodified linesdefaultConfigurationName = Release;};/* End XCConfigurationList section *//* Begin XCRemoteSwiftPackageReference section */FE673FC92A4CDBF7003EF230 /* XCRemoteSwiftPackageReference "keychain-swift" */ = {isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/evgenyneu/keychain-swift.git";requirement = {kind = upToNextMajorVersion;minimumVersion = 20.0.0;};};/* End XCRemoteSwiftPackageReference section *//* Begin XCSwiftPackageProductDependency section */FE673FCA2A4CDBF7003EF230 /* KeychainSwift */ = {isa = XCSwiftPackageProductDependency;package = FE673FC92A4CDBF7003EF230 /* XCRemoteSwiftPackageReference "keychain-swift" */;productName = KeychainSwift;};/* End XCSwiftPackageProductDependency section */};rootObject = FE56FAD52A4C580F008410B4 /* Project object */;}
1234567891011121314{ "pins" : [ { "identity" : "keychain-swift", "kind" : "remoteSourceControl", "location" : "https://github.com/evgenyneu/keychain-swift.git", "state" : { "revision" : "d108a1fa6189e661f91560548ef48651ed8d93b9", "version" : "20.0.0" } } ], "version" : 2}123456<?xml version="1.0" encoding="UTF-8"?><Bucket uuid = "78398B09-67A6-447A-BDF1-6FF7D60370C3" type = "1" version = "2.0"></Bucket>2 unmodified lines3456789101112139 unmodified lines2324252627282930312 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewareimport uvicornfrom Brain.src.router.browser_router import construct_blueprint_browser_apifrom Brain.src.router.train_router import construct_blueprint_train_apifrom Brain.src.router.api import construct_blueprint_apiapp = FastAPI()# Set up CORS middlewareapp.add_middleware(9 unmodified linesapp.include_router(construct_blueprint_browser_api(), prefix="/browser", tags=["ai_browser"])app.include_router(construct_blueprint_train_api(), prefix="/train", tags=["ai_train"])if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)2 unmodified lines34567891011121314151617189 unmodified lines282930313233343536373839404142432 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewareimport uvicorn# from Brain.src.gradio_debug import debug_send_notificationfrom Brain.src.router.browser_router import construct_blueprint_browser_apifrom Brain.src.router.train_router import construct_blueprint_train_apifrom Brain.src.router.email_router import construct_blueprint_email_apifrom Brain.src.router.api import construct_blueprint_apiimport gradio as grimport randomimport timeapp = FastAPI()# Set up CORS middlewareapp.add_middleware(9 unmodified linesapp.include_router(construct_blueprint_browser_api(), prefix="/browser", tags=["ai_browser"])app.include_router(construct_blueprint_train_api(), prefix="/train", tags=["ai_train"])app.include_router(construct_blueprint_email_api(), prefix="/email", tags=["ai_email"])# gradio# CUSTOM_PATH = "/gradio"## app = gr.mount_gradio_app(# app, debug_send_notification, path=f"{CUSTOM_PATH}/sendNotification"# )if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
2 unmodified lines34567815 unmodified lines2425262728293041 unmodified lines727374752 unmodified linespytest==7.3.0async-timeout==4.0.2attrs==22.2.0black==23.3.0CacheControl==0.12.11cachetools==5.3.015 unmodified linesuvicorn==0.21.1frozenlist==1.3.3google-api-core==2.11.0google-api-python-client==2.85.0google-auth==2.17.3google-auth-httplib2==0.1.0google-cloud-core==2.3.241 unmodified linesfaiss-cpu==1.7.4google-search-results==2.4.2tiktoken==0.4.0tiktoken==0.4.02 unmodified lines345678915 unmodified lines2526272829303141 unmodified lines7374757677782 unmodified linespytest==7.3.0async-timeout==4.0.2attrs==22.2.0beautifulsoup4==4.12.2black==23.3.0CacheControl==0.12.11cachetools==5.3.015 unmodified linesuvicorn==0.21.1frozenlist==1.3.3google-api-core==2.11.0google-api-python-client==2.90.0google-auth==2.17.3google-auth-httplib2==0.1.0google-cloud-core==2.3.241 unmodified linesfaiss-cpu==1.7.4google-search-results==2.4.2tiktoken==0.4.0tiktoken==0.4.0gradio-client==0.2.7gradio==3.14.0
.gitignore+2
Android/README.md-1
Android/app/src/main/res/drawable/ic_attachment_48.xmlAdded+5
Brain/README.md+1-6
Brain/logs/activity.logDeleted-82
Brain/src/commands/command.py+5-5
Brain/src/common/assembler.py+16-1
Brain/src/common/program_type.py+14-11
Brain/src/common/utils.py+6
Brain/src/gradio_debug.pyAdded+47
Brain/src/model/requests/request_model.py+29
Brain/src/rising_plugin/gmail/email_plugin.pyAdded+359
Brain/src/rising_plugin/guardrails-config/actions/actions.py+1-107
Brain/src/rising_plugin/guardrails-config/off-security.co+1-1
Brain/src/rising_plugin/llm/llms.py+35-1
Brain/src/rising_plugin/rails_validate.pyAdded+15
Brain/src/rising_plugin/risingplugin.py+109-47
Brain/src/router/api.py+91-3
Brain/src/router/email_router.pyAdded+77
Brain/src/router/train_router.py+27
Brain/src/service/auto_task_service.py+14-2
Brain/src/service/contact_service.py+67-1
Brain/src/service/train_service.py+6
Brain/tests/functional/test_api.py+26
Extension/.idea/.gitignoreDeleted-5
Extension/.idea/Extension.imlDeleted-12
Extension/.idea/inspectionProfiles/Project_Default.xmlDeleted-6
Extension/.idea/modules.xmlDeleted-8
Extension/.idea/vcs.xmlDeleted-6
Extension/src/pages/Content/modules/DraggablePanel.jsx+2
Extension/src/pages/Panel/Message/index.css+14-8
Extension/src/pages/Panel/Panel.css+15-2
Extension/src/pages/Panel/Panel.jsx+24-12
README.md+1-5
WatchApp/WatchApp Watch App/Assets.xcassets/AccentColor.colorset/Contents.jsonDeleted-11
WatchApp/WatchApp Watch App/Assets.xcassets/AppIcon.appiconset/Contents.jsonDeleted-13
WatchApp/WatchApp Watch App/Assets.xcassets/Contents.jsonDeleted-6
WatchApp/WatchApp Watch App/Components/ChatMessageRow.swiftAdded+57
WatchApp/WatchApp Watch App/ContentView.swiftDeleted-73
WatchApp/WatchApp Watch App/MainView.swiftAdded+28
WatchApp/WatchApp Watch App/Pages/ChatView.swiftAdded+112
WatchApp/WatchApp Watch App/Pages/SettingView.swiftAdded+46
WatchApp/WatchApp Watch App/WatchAppApp.swift+1-1
WatchApp/WatchApp.xcodeproj/project.pbxproj+59-20
WatchApp/WatchApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedAdded+14
WatchApp/WatchApp.xcodeproj/project.xcworkspace/xcuserdata/darkhorse.xcuserdatad/UserInterfaceState.xcuserstate
WatchApp/WatchApp.xcodeproj/xcuserdata/darkhorse.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlistAdded+6
app.py+14-2
requirements.txt+5-2