gizemsarsinlar commited on
Commit
5fe9221
·
verified ·
1 Parent(s): d4c42c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -79
app.py CHANGED
@@ -1,29 +1,16 @@
1
  import os
2
- from openai import AsyncOpenAI # importing openai for API usage
3
- import chainlit as cl # importing chainlit for our app
4
- from chainlit.prompt import Prompt, PromptMessage # importing prompt tools
5
- from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
6
- from dotenv import load_dotenv
7
- import asyncio
8
- import textract # importing textract for document processing
9
 
10
  # Load OpenAI API key from environment variables
11
  api_key = os.getenv("OPENAI_API_KEY")
12
 
13
- # Templates for ChatOpenAI interaction
14
- system_template = """You are a helpful assistant who always speaks in a pleasant tone and answers based on the provided document!
15
- """
16
-
17
- user_template = """{input}
18
- Use the document content to respond to the user query step by step.
19
- """
20
-
21
  # Function to extract text from uploaded documents
22
- async def extract_text_from_file(file):
23
- # Extract text from the uploaded file using textract
24
- return textract.process(file).decode('utf-8')
25
 
26
- # Function to start the chat session
27
  @cl.on_chat_start
28
  async def start_chat():
29
  settings = {
@@ -34,72 +21,51 @@ async def start_chat():
34
  "frequency_penalty": 0,
35
  "presence_penalty": 0,
36
  }
37
-
38
  cl.user_session.set("settings", settings)
39
 
40
- # Welcome message with file upload option
41
  await cl.Message(content="Welcome! Please upload a document to begin.").send()
42
 
43
- # Function to handle uploaded files
44
- @cl.on_file_upload
45
- async def on_file_upload(files: list):
46
- # Handle the uploaded files, assuming it's the first file
47
- if files:
48
- file = files[0]
49
- file_content = await extract_text_from_file(file.path)
50
-
51
- # Save document content in session for later use
52
- cl.user_session.set("document_content", file_content)
53
-
54
- # Inform the user that the document was successfully uploaded
55
- await cl.Message(content=f"Document '{file.name}' uploaded successfully! You can now ask questions based on the document content.").send()
56
-
57
- # Function to handle user messages
58
- @cl.on_message
59
  async def main(message: cl.Message):
60
- settings = cl.user_session.get("settings")
61
- document_content = cl.user_session.get("document_content", "")
62
-
63
- if not document_content:
64
- # If no document is uploaded, prompt the user to upload one
65
- await cl.Message(content="Please upload a document first.").send()
66
- return
67
 
68
- client = AsyncOpenAI()
69
-
70
- prompt = Prompt(
71
- provider=ChatOpenAI.id,
72
- messages=[
73
- PromptMessage(
74
- role="system",
75
- template=system_template,
76
- formatted=system_template,
77
- ),
78
- PromptMessage(
79
- role="user",
80
- template=user_template,
81
- formatted=user_template.format(input=message.content),
82
- ),
83
- ],
84
- inputs={"input": message.content, "document": document_content},
85
- settings=settings,
86
- )
87
-
88
- msg = cl.Message(content="")
89
-
90
- # Call OpenAI
91
- async for stream_resp in await client.chat.completions.create(
92
- messages=[m.to_openai() for m in prompt.messages], stream=True, **settings
93
- ):
94
- token = stream_resp.choices[0].delta.content
95
- if not token:
96
- token = ""
97
- await msg.stream_token(token)
98
 
99
- # Update the prompt object with the completion
100
- prompt.completion = msg.content
101
- msg.prompt = prompt
 
 
 
 
102
 
103
- # Send and close the message stream
104
- await msg.send()
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import chainlit as cl # Chainlit import
3
+ from openai import AsyncOpenAI # OpenAI API
4
+ import textract # For extracting text from documents
 
 
 
 
5
 
6
  # Load OpenAI API key from environment variables
7
  api_key = os.getenv("OPENAI_API_KEY")
8
 
 
 
 
 
 
 
 
 
9
  # Function to extract text from uploaded documents
10
+ async def extract_text_from_file(file_path):
11
+ return textract.process(file_path).decode('utf-8')
 
12
 
13
+ # Chat initialization
14
  @cl.on_chat_start
15
  async def start_chat():
16
  settings = {
 
21
  "frequency_penalty": 0,
22
  "presence_penalty": 0,
23
  }
 
24
  cl.user_session.set("settings", settings)
25
 
 
26
  await cl.Message(content="Welcome! Please upload a document to begin.").send()
27
 
28
+ # This handles incoming files manually (instead of on_file_upload)
29
+ @cl.on_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  async def main(message: cl.Message):
31
+ if message.attachments: # Check if the message contains file attachments
32
+ uploaded_file = message.attachments[0]
33
+ file_path = uploaded_file['path']
 
 
 
 
34
 
35
+ # Extract text from the uploaded document
36
+ file_content = await extract_text_from_file(file_path)
37
+
38
+ # Store document content in user session
39
+ cl.user_session.set("document_content", file_content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ await cl.Message(content=f"Document '{uploaded_file['name']}' uploaded successfully! You can now ask questions based on the document content.").send()
42
+ else:
43
+ document_content = cl.user_session.get("document_content", "")
44
+
45
+ if not document_content:
46
+ await cl.Message(content="Please upload a document first.").send()
47
+ return
48
 
49
+ settings = cl.user_session.get("settings")
50
+ client = AsyncOpenAI()
51
 
52
+ # Create the prompt for OpenAI based on user message and document content
53
+ prompt = f"Document Content: {document_content}\n\nUser Query: {message.content}"
54
+
55
+ msg = cl.Message(content="")
56
+
57
+ # Send prompt to OpenAI and stream response
58
+ async for stream_resp in await client.chat.completions.create(
59
+ model=settings["model"],
60
+ messages=[{"role": "system", "content": "Answer based on the provided document."},
61
+ {"role": "user", "content": prompt}],
62
+ stream=True,
63
+ **settings,
64
+ ):
65
+ token = stream_resp.choices[0].delta.content
66
+ if not token:
67
+ token = ""
68
+ await msg.stream_token(token)
69
+
70
+ # Send final response
71
+ await msg.send()