File size: 10,089 Bytes
e036bfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from langchain_community.llms import HuggingFacePipeline
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate
import warnings
import os

# Suppress warnings
warnings.filterwarnings("ignore")
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'

# Model Configuration
MODEL_NAME = "gpt2"
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"

def initialize_models():
    """Initialize language model and embedding model."""
    try:
        # Determine device
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print(f"Using device: {device}")

        # Load model and tokenizer
        model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
        tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

        # Create pipeline
        text_generation_pipeline = pipeline(
            "text-generation",
            model=model,
            tokenizer=tokenizer,
            max_new_tokens=512,
            temperature=0.7,
            repetition_penalty=1.1
        )

        # Langchain LLM
        llm = HuggingFacePipeline(pipeline=text_generation_pipeline)

        # Embedding model
        embedding_model = HuggingFaceEmbeddings(
            model_name=EMBEDDING_MODEL,
            model_kwargs={'device': str(device)}
        )

        return llm, embedding_model, model, tokenizer

    except Exception as e:
        print(f"Model initialization error: {e}")
        return None, None, None, None

# Initialize models
llm, embedding_model, model, tokenizer = initialize_models()

# Global variables for RAG state
rag_retriever = None
document_loaded = False
loaded_doc_name = "No document loaded"

def setup_rag_pipeline(doc_text, chunk_size=1000, chunk_overlap=150):
    """Loads text, chunks, embeds, creates FAISS index, and sets up retriever."""
    global rag_retriever, document_loaded, loaded_doc_name

    if not doc_text or not isinstance(doc_text, str) or len(doc_text.strip()) == 0:
        return "Error: No text provided or invalid input."

    try:
        # Text splitting
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=chunk_size,
            chunk_overlap=chunk_overlap,
            length_function=len,
        )
        docs = text_splitter.split_text(doc_text)

        if not docs:
            return "Error: Text splitting resulted in no documents."

        # Create embeddings and FAISS index
        vector_store = FAISS.from_texts(docs, embedding_model)
        rag_retriever = vector_store.as_retriever(search_kwargs={"k": 3})

        document_loaded = True
        loaded_doc_name = f"Document processed ({len(doc_text)} chars, {len(docs)} chunks)."
        return loaded_doc_name

    except Exception as e:
        document_loaded = False
        rag_retriever = None
        return f"Error processing document: {e}"

def answer_question(question):
    """Answers a question using the loaded RAG pipeline."""
    if llm is None or embedding_model is None:
        return "Error: Models not initialized properly."

    if not document_loaded or rag_retriever is None:
        return "Error: Please load a document before asking questions."

    if not question or not isinstance(question, str) or len(question.strip()) == 0:
        return "Error: Please enter a question."

    try:
        # Define a prompt template
        template = """You are a helpful assistant answering questions based on the provided context.
        Use only the information given in the context below to answer the question.
        If the context doesn't contain the answer, say "The provided context does not contain the answer to this question."
        Be concise.

        Context:
        {context}

        Question: {question}
        Answer:"""

        QA_CHAIN_PROMPT = PromptTemplate(
            input_variables=["context", "question"],
            template=template,
        )

        # Create RetrievalQA chain
        qa_chain = RetrievalQA.from_chain_type(
            llm=llm,
            chain_type="stuff",
            retriever=rag_retriever,
            chain_type_kwargs={"prompt": QA_CHAIN_PROMPT},
            return_source_documents=False
        )

        result = qa_chain.invoke({"query": question})
        answer = result.get("result", str(result)) if isinstance(result, dict) else str(result)

        return answer.strip()

    except Exception as e:
        return f"Error answering question: {e}"

def summarize_text(text_to_summarize, max_length=150, min_length=30):
    """Summarizes the provided text using the LLM."""
    if llm is None:
        return "Error: Models not initialized properly."

    if not text_to_summarize or not isinstance(text_to_summarize, str) or len(text_to_summarize.strip()) == 0:
        return "Error: Please enter text to summarize."

    try:
        # Create a prompt for summarization
        prompt = f"Summarize the following text concisely, aiming for {min_length} to {max_length} words:\n\n{text_to_summarize}"

        # Use the pipeline directly for summarization
        summary_pipeline = pipeline(
            "text-generation",
            model=model,
            tokenizer=tokenizer,
            max_new_tokens=max_length,
            temperature=0.5
        )

        # Generate summary
        summary_result = summary_pipeline(prompt, max_length=max_length)[0]['generated_text']

        # Extract the actual summary part
        summary = summary_result.replace(prompt, '').strip()

        return summary

    except Exception as e:
        return f"Error summarizing text: {e}"

def draft_text(instructions):
    """Drafts text based on user instructions using the LLM."""
    if llm is None:
        return "Error: Models not initialized properly."

    if not instructions or not isinstance(instructions, str) or len(instructions.strip()) == 0:
        return "Error: Please enter drafting instructions."

    try:
        # Drafting prompt
        prompt = f"Write the following based on these instructions:\n\n{instructions}"

        # Use the pipeline for text generation
        draft_pipeline = pipeline(
            "text-generation",
            model=model,
            tokenizer=tokenizer,
            max_new_tokens=500,
            temperature=0.7
        )

        # Generate draft
        draft_result = draft_pipeline(prompt, max_length=500)[0]['generated_text']

        # Extract the actual draft part
        draft = draft_result.replace(prompt, '').strip()

        return draft

    except Exception as e:
        return f"Error drafting text: {e}"

# Gradio Interface
def create_gradio_interface():
    with gr.Blocks(theme=gr.themes.Soft()) as iface:
        gr.Markdown("# Workplace Assistant (GPT-2 Demo)")
        gr.Markdown("Powered by GPT-2 and Langchain")

        with gr.Tabs():
            # Document Q&A Tab
            with gr.TabItem("Document Q&A (RAG)"):
                gr.Markdown("Load text content from a document, then ask questions about it.")
                doc_input = gr.Textbox(label="Paste Document Text Here", lines=10, placeholder="Paste the full text content you want to query...")
                load_button = gr.Button("Process Document")
                status_output = gr.Textbox(label="Document Status", value=loaded_doc_name, interactive=False)
                question_input = gr.Textbox(label="Your Question", placeholder="Ask a question about the document...")
                ask_button = gr.Button("Ask Question")
                answer_output = gr.Textbox(label="Answer", lines=5, interactive=False)

                load_button.click(
                    fn=setup_rag_pipeline,
                    inputs=[doc_input],
                    outputs=[status_output]
                )
                ask_button.click(
                    fn=answer_question,
                    inputs=[question_input],
                    outputs=[answer_output]
                )

            # Summarization Tab
            with gr.TabItem("Summarization"):
                gr.Markdown("Paste text to get a concise summary.")
                summarize_input = gr.Textbox(label="Text to Summarize", lines=10, placeholder="Paste text here...")
                summarize_button = gr.Button("Summarize")
                summary_output = gr.Textbox(label="Summary", lines=5, interactive=False)

                with gr.Accordion("Advanced Options", open=False):
                    max_len_slider = gr.Slider(minimum=20, maximum=300, value=150, step=10, label="Max Summary Length (approx words)")
                    min_len_slider = gr.Slider(minimum=10, maximum=100, value=30, step=5, label="Min Summary Length (approx words)")

                summarize_button.click(
                    fn=summarize_text,
                    inputs=[summarize_input, max_len_slider, min_len_slider],
                    outputs=[summary_output]
                )

            # Drafting Tab
            with gr.TabItem("Drafting Assistant"):
                gr.Markdown("Provide instructions for the AI to draft text.")
                draft_instructions = gr.Textbox(label="Drafting Instructions", lines=5, placeholder="e.g., Draft a short, friendly email to the team.")
                draft_button = gr.Button("Generate Draft")
                draft_output = gr.Textbox(label="Generated Draft", lines=10, interactive=False)

                draft_button.click(
                    fn=draft_text,
                    inputs=[draft_instructions],
                    outputs=[draft_output]
                )

    return iface

# Launch the interface
if __name__ == "__main__":
    try:
        iface = create_gradio_interface()
        iface.launch(share=True, debug=True)
    except Exception as e:
        print(f"Error launching Gradio interface: {e}")