Spaces:
Build error

File size: 5,843 Bytes
788a6a1
01f7a3c
298bb7e
788a6a1
298bb7e
01f7a3c
0c4091f
 
 
 
01f7a3c
6cd76e5
01f7a3c
6fb4df1
01f7a3c
54aa9a2
0c4091f
6fb4df1
788a6a1
54aa9a2
298bb7e
 
788a6a1
0c4091f
 
788a6a1
0c4091f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788a6a1
54aa9a2
298bb7e
788a6a1
0c4091f
6fb4df1
0c4091f
6fb4df1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c4091f
6fb4df1
 
0c4091f
 
6fb4df1
 
 
 
 
0c4091f
 
6fb4df1
 
0c4091f
 
 
6fb4df1
 
298bb7e
 
dfff175
 
54aa9a2
6fb4df1
0c4091f
b618005
dfff175
b618005
 
dfff175
 
 
 
 
 
 
 
 
0c4091f
 
 
6fb4df1
dfff175
0c4091f
62587d9
dfff175
 
 
b618005
54aa9a2
298bb7e
0c4091f
298bb7e
54aa9a2
 
 
 
 
 
0c4091f
 
298bb7e
54aa9a2
0c4091f
 
 
6fb4df1
0c4091f
 
 
6fb4df1
 
0c4091f
298bb7e
54aa9a2
0c4091f
 
 
 
 
 
 
 
298bb7e
54aa9a2
298bb7e
54aa9a2
298bb7e
0c4091f
 
298bb7e
0c4091f
54aa9a2
788a6a1
6fb4df1
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
import os
import sys
import logging
import gradio as gr
import openai
import requests
import shutil
import pandas as pd
from docx import Document as DocxDocument
import fitz  # PyMuPDF
from pinecone import Pinecone, ServerlessSpec
from llama_index.core import VectorStoreIndex, StorageContext, Document,SimpleDirectoryReader
from llama_index.vector_stores.pinecone import PineconeVectorStore
import uuid

# --- Logging ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# --- Set API Keys from Environment Variables ---
openai.api_key = os.environ.get("OPENAI_API_KEY")
pinecone_api_key = os.environ.get("PINECONE_API_KEY")

if not openai.api_key or not pinecone_api_key:
    raise ValueError("OPENAI_API_KEY and PINECONE_API_KEY must be set in environment variables.")

# --- Initialize Pinecone ---
try:
    pc = Pinecone(api_key=pinecone_api_key)
    index_name = "hf-doc-qa"
    dimension = 1536

    # Create the index if it doesn't exist
    if index_name not in [idx['name'] for idx in pc.list_indexes()]:
        logger.info(f"Creating Pinecone index: {index_name}")
        pc.create_index(
            name=index_name,
            dimension=dimension,
            metric="euclidean",
            spec=ServerlessSpec(cloud="aws", region="us-east-1"),
        )

    pinecone_index = pc.Index(index_name)
    vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
    storage_context = StorageContext.from_defaults(vector_store=vector_store)
except Exception as e:
    logger.error(f"Failed to initialize Pinecone: {str(e)}")
    raise

# --- Global Index ---
index = None

# --- Document Processing Functions ---
def extract_text_from_pdf(file_path):
    """Extract text from a PDF file using PyMuPDF."""
    try:
        doc = fitz.open(file_path)
        text = ""
        for page in doc:
            text += page.get_text()
        doc.close()
        return text
    except Exception as e:
        logger.error(f"Error processing PDF {file_path}: {str(e)}")
        return None

def extract_text_from_docx(file_path):
    """Extract text from a DOCX file."""
    try:
        doc = DocxDocument(file_path)
        text = "\n".join([para.text for para in doc.paragraphs if para.text])
        return text
    except Exception as e:
        logger.error(f"Error processing DOCX {file_path}: {str(e)}")
        return None

def extract_text_from_csv(file_path):
    """Extract text from a CSV file using pandas."""
    try:
        df = pd.read_csv(file_path)
        # Convert DataFrame to a string representation
        text = df.to_string(index=False)
        return text
    except Exception as e:
        logger.error(f"Error processing CSV {file_path}: {str(e)}")
        return None

def extract_text_from_txt(file_path):
    """Extract text from a TXT file."""
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception as e:
        logger.error(f"Error processing TXT {file_path}: {str(e)}")
        return None

def process_documents(files):
    global index
    data_dir = "./.data"
    os.makedirs(data_dir, exist_ok=True)

    try:
        for file in files:
            # Gradio gives a temporary file path
            file_ext = os.path.splitext(file.name)[1].lower()
            dest_path = os.path.join(data_dir, os.path.basename(file.name))
            shutil.copy(file.name, dest_path)

        # Load files using SimpleDirectoryReader
        documents = SimpleDirectoryReader(input_dir=data_dir).load_data()

        # Create vector index
        vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
        storage_context = StorageContext.from_defaults(vector_store=vector_store)
        index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)

        logger.info("Documents indexed successfully")
        return "โœ… Documents indexed successfully. You can now ask questions."

    except Exception as e:
        logger.error(f"Error processing documents: {str(e)}")
        return f"Error: {str(e)}"

    finally:
        # Optionally clean up .data folder after indexing
        shutil.rmtree(data_dir)


def query_doc(prompt):
    """Query the indexed documents."""
    if index is None:
        return "โš ๏ธ Please upload and index documents first."
    
    try:
        response = index.as_query_engine().query(prompt)
        return str(response)
    except Exception as e:
        logger.error(f"Error querying documents: {str(e)}")
        return f"Error: {str(e)}"

# --- Gradio Interface ---
with gr.Blocks(title="Document QA with LlamaIndex + Pinecone") as demo:
    # Add company logo
    gr.HTML(
        """
        <div style='text-align: center;'>
            <img src='https://1000logos.net/wp-content/uploads/2021/12/Zain-logo.png' alt='Zain Logo' style='max-width: 200px; margin-bottom: 20px;'>
        </div>
        """
    )
    gr.Markdown("## ๐Ÿ“„ Document QA Chatbot\nUpload your .txt, .pdf, .docx, or .csv files and ask questions based on the content.")

    with gr.Row():
        file_input = gr.File(
            label="Upload Documents",
            file_types=[".txt", ".pdf", ".docx", ".csv"],
            file_count="multiple"
        )
        upload_button = gr.Button("๐Ÿ“ฅ Index Documents")

    status_output = gr.Textbox(label="Indexing Status", interactive=False)

    upload_button.click(fn=process_documents, inputs=[file_input], outputs=[status_output])

    gr.Markdown("---")

    question_input = gr.Textbox(label="Ask a Question", placeholder="What is the document about?")
    answer_output = gr.Textbox(label="Answer")

    ask_button = gr.Button("๐Ÿ’ฌ Get Answer")
    ask_button.click(fn=query_doc, inputs=question_input, outputs=answer_output)

demo.launch()