File size: 7,157 Bytes
ead511a
 
fd85cd0
e35dc50
 
 
 
 
 
 
14a0e81
ead511a
528891b
ead511a
528891b
16a0a0c
ead511a
16a0a0c
ead511a
39ea5ba
fd85cd0
16a0a0c
 
ead511a
e35dc50
 
 
16a0a0c
 
 
 
 
 
39ea5ba
16a0a0c
ead511a
16a0a0c
41f0a85
16a0a0c
 
41f0a85
 
 
 
 
16a0a0c
 
e35dc50
16a0a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd85cd0
16a0a0c
 
 
 
 
ead511a
16a0a0c
 
e35dc50
16a0a0c
 
 
 
 
 
24c5a32
2bb0e5a
 
 
24c5a32
 
 
16a0a0c
 
 
 
 
e35dc50
 
 
 
 
24c5a32
 
 
e35dc50
 
 
 
 
24c5a32
e35dc50
 
 
 
 
 
 
 
 
 
 
 
 
1485585
 
 
 
 
 
e35dc50
2bb0e5a
e35dc50
2bb0e5a
 
 
e35dc50
2bb0e5a
14a0e81
 
 
 
 
 
 
b75e8c0
 
 
 
2bb0e5a
1485585
 
 
 
b75e8c0
 
 
 
 
1485585
b75e8c0
 
 
 
1485585
b75e8c0
 
 
 
1485585
b75e8c0
 
 
41f0a85
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import streamlit as st
from openai import OpenAI
import time
import os
import re
import pandas as pd
import PyPDF2
from datetime import datetime
from pydub import AudioSegment
from docx import Document
from io import BytesIO

st.set_page_config(page_title="Schlager ContractAi")

st.title("Schlager ContractAi")
st.caption("Chat with your contract or manage meeting minutes")

# Sidebar for API Key input
with st.sidebar:
    OPENAI_API_KEY = st.text_input("Enter your C2 Group of Technologies Access Key", type="password")

# Tabs for Contract and Minutes
tab1, tab2 = st.tabs(["Contract", "Minutes"])

SUPPORTED_AUDIO_FORMATS = (".mp3", ".wav", ".m4a")
SUPPORTED_TEXT_FORMATS = (".txt", ".docx", ".csv", ".xlsx", ".pdf")

with tab1:
    st.subheader("Contract Chat")
    
    if OPENAI_API_KEY:
        client = OpenAI(api_key=OPENAI_API_KEY)
    else:
        st.error("Please enter your C2 Group of Technologies Access Key to continue.")
        st.stop()

    ASSISTANT_ID = "asst_rd9h8PfYuOmHbkvOF3RTmVfn"
    
    if "messages" not in st.session_state:
        st.session_state["messages"] = []
    
    if st.button("Clear Chat"):
        st.session_state["messages"] = []
        st.rerun()
    
    for message in st.session_state.messages:
        role, content = message["role"], message["content"]
        st.chat_message(role).write(content)

    if prompt := st.chat_input():
        st.session_state.messages.append({"role": "user", "content": prompt})
        st.chat_message("user").write(prompt)

        try:
            thread = client.beta.threads.create()
            thread_id = thread.id
            client.beta.threads.messages.create(
                thread_id=thread_id,
                role="user",
                content=prompt
            )
            
            run = client.beta.threads.runs.create(
                thread_id=thread_id,
                assistant_id=ASSISTANT_ID
            )

            while True:
                run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
                if run_status.status == "completed":
                    break
                time.sleep(1)

            messages = client.beta.threads.messages.list(thread_id=thread_id)
            assistant_message = messages.data[0].content[0].text.value
            st.chat_message("assistant").write(assistant_message)
            st.session_state.messages.append({"role": "assistant", "content": assistant_message})
        except Exception as e:
            st.error(f"Error: {str(e)}")

with tab2:
    st.subheader("Minutes")
    
    if "generated_minutes" not in st.session_state:
        st.session_state["generated_minutes"] = ""

    uploaded_files = st.file_uploader("Upload meeting minutes (PDF/DOCX/Audio)", 
                                      type=["pdf", "docx", "mp3", "wav", "m4a"], 
                                      accept_multiple_files=True)
    
    if uploaded_files:
        st.write("### Uploaded Files:")
        for uploaded_file in uploaded_files:
            st.write(f"- {uploaded_file.name}")
        
        combined_text = ""
        for uploaded_file in uploaded_files:
            if uploaded_file.name.lower().endswith(SUPPORTED_AUDIO_FORMATS):
                audio = AudioSegment.from_file(uploaded_file)
                temp_audio_path = "temp_audio.mp3"
                audio.export(temp_audio_path, format="mp3")
                with open(temp_audio_path, "rb") as audio_file:
                    transcription = client.audio.transcriptions.create(
                        model="whisper-1",
                        file=audio_file
                    )
                combined_text += transcription.text + "\n"
                os.remove(temp_audio_path)
            else:
                if uploaded_file.name.endswith(".docx"):
                    doc = Document(uploaded_file)
                    combined_text += "\n".join([para.text for para in doc.paragraphs])
                elif uploaded_file.name.endswith(".pdf"):
                    pdf_reader = PyPDF2.PdfReader(uploaded_file)
                    combined_text += "\n".join([page.extract_text() for page in pdf_reader.pages if page.extract_text()])
        
        if combined_text:
            st.write("### Transcribed and Extracted Text:")
            st.text_area("Meeting Transcript", combined_text, height=300)
            
            if st.button("Generate Meeting Minutes"):
                response = client.chat.completions.create(
                    model="gpt-4-turbo",
                    messages=[
                        {"role": "system", "content": "You are an AI assistant that generates professional meeting minutes."},
                        {"role": "user", "content": f"Summarize the following into structured meeting minutes:\n{combined_text}"}
                    ]
                )
                st.session_state["generated_minutes"] = response.choices[0].message.content
                st.write("### Meeting Minutes:")
                st.text_area("Generated Minutes", st.session_state["generated_minutes"], height=300)
            
            if st.session_state["generated_minutes"]:
                doc = Document()
                doc.add_paragraph(st.session_state["generated_minutes"])
                
                docx_io = BytesIO()
                doc.save(docx_io)
                docx_io.seek(0)
                
                st.download_button(label="Download Meeting Minutes", 
                                   data=docx_io, 
                                   file_name="Meeting_Minutes.docx", 
                                   mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                
                if st.button("Contract Analysis"):
                    analysis_prompt = "Analyse this data and provide any insights, risks and relevant data based on the contract that we need to be aware of.\n" + st.session_state["generated_minutes"]
                    thread = client.beta.threads.create()
                    thread_id = thread.id
                    client.beta.threads.messages.create(
                        thread_id=thread_id,
                        role="user",
                        content=analysis_prompt
                    )
                    
                    run = client.beta.threads.runs.create(
                        thread_id=thread_id,
                        assistant_id=ASSISTANT_ID
                    )
                    
                    while True:
                        run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
                        if run_status.status == "completed":
                            break
                        time.sleep(1)
                    
                    messages = client.beta.threads.messages.list(thread_id=thread_id)
                    analysis_output = messages.data[0].content[0].text.value
                    
                    st.write("### Contract Analysis Output:")
                    st.text_area("Contract Analysis", analysis_output, height=300)