Spaces:
Sleeping
Sleeping
Download app.py from marcelosoaresds/teste: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/marcelosoaresds/teste/resolve/main/app.py
- Command line
-
hf download hf://spaces/marcelosoaresds/teste/app.py
-
curl -L -o app.py https://huggingface.co/spaces/marcelosoaresds/teste/resolve/main/app.py
10 kB
| import gradio as gr | |
| import os | |
| import pypdf | |
| # import docx # Uncomment if handling .docx | |
| import numpy as np | |
| from sentence_transformers import SentenceTransformer | |
| from annoy import AnnoyIndex | |
| import pickle | |
| import google.generativeai as genai # Use google.generativeai for deployment | |
| def handle_document_upload(file_path): | |
| """ | |
| Handles uploaded text documents by extracting and chunking text. | |
| Args: | |
| file_path: The path to the uploaded file. | |
| Returns: | |
| A list of text chunks. | |
| Raises: | |
| ValueError: If the file format is not supported. | |
| """ | |
| file_extension = os.path.splitext(file_path)[1].lower() | |
| text = "" | |
| if file_extension == '.pdf': | |
| try: | |
| with open(file_path, 'rb') as file: | |
| reader = pypdf.PdfReader(file) | |
| for page_num in range(len(reader.pages)): | |
| text += reader.pages[page_num].extract_text() | |
| except Exception as e: | |
| print(f"Error reading PDF file: {e}") | |
| return [] | |
| elif file_extension == '.txt': | |
| try: | |
| with open(file_path, 'r', encoding='utf-8') as file: | |
| text = file.read() | |
| except Exception as e: | |
| print(f"Error reading TXT file: {e}") | |
| return [] | |
| # elif file_extension == '.docx': | |
| # try (edited) | |
| # doc = docx.Document(file_path) | |
| # for paragraph in doc.paragraphs: | |
| # text += paragraph.text + "\n" | |
| # except Exception as e: | |
| # print(f"Error reading DOCX file: {e)}") | |
| # return [] | |
| else: | |
| raise ValueError(f"Unsupported file format: {file_extension}") | |
| # Simple chunking by splitting into paragraphs | |
| # You might need a more sophisticated chunking strategy | |
| chunks = [chunk.strip() for chunk in text.split('\n\n') if chunk.strip()] | |
| # Further split large chunks if necessary (e.g., by sentence or character count) | |
| # This is a basic example, adjust chunk_size as needed | |
| max_chunk_size = 500 | |
| processed_chunks = [] | |
| for chunk in chunks: | |
| if len(chunk) > max_chunk_size: | |
| # Split by sentence or a fixed character length within paragraphs | |
| sub_chunks = [] | |
| current_sub_chunk = "" | |
| # Simple sentence split based on '.' | |
| sentences = chunk.split('.') | |
| for i, sentence in enumerate(sentences): | |
| # Add the sentence and a '.' if it's not the last one | |
| sentence_to_add = sentence.strip() | |
| if sentence_to_add: | |
| # Add the period back to the sentence if it wasn't the last one | |
| if i < len(sentences) - 1: | |
| sentence_to_add += "." | |
| if len(current_sub_chunk) + len(sentence_to_add) + (1 if current_sub_chunk else 0) <= max_chunk_size: | |
| if current_sub_chunk: | |
| current_sub_chunk += " " + sentence_to_add | |
| else: | |
| current_sub_chunk = sentence_to_add | |
| else: | |
| if current_sub_chunk: | |
| processed_chunks.append(current_sub_chunk) | |
| current_sub_chunk = sentence_to_add | |
| if current_sub_chunk: | |
| processed_chunks.append(current_sub_chunk) | |
| else: | |
| processed_chunks.append(chunk) | |
| return processed_chunks | |
| def create_embeddings_and_index(chunks, index_file="index.ann", chunks_file="chunks.pkl"): | |
| """ | |
| Generates embeddings for text chunks, creates an Annoy index, and saves them. | |
| Args: | |
| chunks: A list of text chunks. | |
| index_file: Filename to save the Annoy index. | |
| chunks_file: Filename to save the original text chunks. | |
| """ | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| embeddings = model.encode(chunks) | |
| # Get the dimension of the embeddings | |
| embedding_dim = embeddings.shape[1] | |
| # Create an Annoy index | |
| annoy_index = AnnoyIndex(embedding_dim, 'angular') # Using 'angular' distance metric | |
| for i, embedding in enumerate(embeddings): | |
| annoy_index.add_item(i, embedding) | |
| # Build the index with 10 trees (adjust based on your needs) | |
| annoy_index.build(10) | |
| # Save the index and chunks | |
| annoy_index.save(index_file) | |
| with open(chunks_file, 'wb') as f: | |
| pickle.dump(chunks, f) | |
| print(f"Index saved to {index_file}") | |
| print(f"Chunks saved to {chunks_file}") | |
| def load_index_and_chunks(index_file="index.ann", chunks_file="chunks.pkl"): | |
| """ | |
| Loads the Annoy index and text chunks from saved files. | |
| Args: | |
| index_file: Filename of the saved Annoy index. | |
| chunks_file: Filename of the saved text chunks. | |
| Returns: | |
| A tuple containing the loaded Annoy index and the list of text chunks. | |
| Returns (None, None) if files are not found. | |
| """ | |
| if not os.path.exists(index_file) or not os.path.exists(chunks_file): | |
| print("Index or chunks file not found.") | |
| return None, None | |
| with open(chunks_file, 'rb') as f: | |
| chunks = pickle.load(f) | |
| # Need to know the dimension of the embeddings to load the index | |
| # We can infer this from the loaded embeddings if we save them, | |
| # or simply assume a fixed dimension based on the model used. | |
| # For simplicity, let's assume a fixed dimension based on 'all-MiniLM-L6-v2' | |
| embedding_dim = 384 # Dimension for 'all-MiniLM-L6-v2' | |
| loaded_index = AnnoyIndex(embedding_dim, 'angular') | |
| loaded_index.load(index_file) | |
| print("Index and chunks loaded successfully.") | |
| return loaded_index, chunks | |
| def answer_query_with_context(query, annoy_index, chunks, sentence_transformer_model, language_model_name, n_neighbors=5): | |
| """ | |
| Answers a user query by finding relevant text chunks and using a language model. | |
| Args: | |
| query: The user's query string. | |
| annoy_index: The loaded Annoy index. | |
| chunks: The list of original text chunks. | |
| sentence_transformer_model: The loaded SentenceTransformer model. | |
| language_model_name: The name of the language model to use. | |
| n_neighbors: The number of nearest neighbors to retrieve from the index. | |
| Returns: | |
| The generated answer from the language model. | |
| """ | |
| # Generate embedding for the query | |
| query_embedding = sentence_transformer_model.encode(query) | |
| # Find the top N most similar text chunks | |
| neighbor_indices = annoy_index.get_nns_by_vector(query_embedding, n_neighbors) | |
| relevant_chunks = [chunks[i] for i in neighbor_indices] | |
| # Construct the prompt for the language model | |
| context = "\n\n".join(relevant_chunks) | |
| prompt = f"""Based on the following text, answer the user's question. | |
| If you cannot find the answer in the provided text, state that you cannot answer based on the given information. | |
| Provided text: | |
| {context} | |
| User question: | |
| {query} | |
| Answer:""" | |
| # Use the language model to generate the answer | |
| try: | |
| # Ensure ai is available in the environment or mock it for local testing | |
| if 'ai' in globals(): | |
| response = ai.generate_text(prompt, model_name=language_model_name) | |
| return response | |
| else: | |
| return "AI model not available in this environment." | |
| except Exception as e: | |
| print(f"Error generating text with language model: {e}") | |
| return "An error occurred while generating the answer." | |
| def gradio_interface_logic(uploaded_file, question): | |
| """ | |
| Core logic for the Gradio interface. | |
| Args: | |
| uploaded_file: The file object uploaded by the user. | |
| question: The user's question as a string. | |
| Returns: | |
| The generated answer as a string. | |
| """ | |
| if uploaded_file is None: | |
| return "Please upload a document first." | |
| file_path = uploaded_file.name | |
| try: | |
| # Step 3: Call handle_document_upload to get text chunks | |
| chunks = handle_document_upload(file_path) | |
| if not chunks: | |
| return "Could not extract text from the document. Please ensure it's a supported format (.pdf, .txt) and not empty." | |
| # Step 4: Create embeddings and index | |
| # Note: In a real deployment, you might want to handle indexing outside the main | |
| # Gradio function to avoid re-indexing on every query. For simplicity here, | |
| # we recreate the index each time. | |
| create_embeddings_and_index(chunks) | |
| # Step 5: Load the created index and chunks | |
| loaded_index, loaded_chunks = load_index_and_chunks() | |
| if loaded_index is None or loaded_chunks is None: | |
| return "Could not load the index or chunks. An error occurred during processing." | |
| # Step 6: Load the SentenceTransformer model | |
| loaded_sentence_transformer_model = SentenceTransformer('all-MiniLM-L6-v2') | |
| # Step 7: Call answer_query_with_context | |
| # Use the selected model from the Model Selection step | |
| selected_model_name = 'google/gemini-2.5-pro' # Make sure this model name is available | |
| answer = answer_query_with_context(question, loaded_index, loaded_chunks, loaded_sentence_transformer_model, selected_model_name) | |
| # Step 8: Return the generated answer | |
| return answer | |
| except ValueError as e: | |
| return f"Error: {e}" | |
| except Exception as e: | |
| return f"An unexpected error occurred: {e}" | |
| # Step 9 & 10: Create a Gradio interface | |
| interface = gr.Interface( | |
| fn=gradio_interface_logic, | |
| inputs=[ | |
| gr.File(label="Upload Document (.pdf, .txt)", file_types=[".pdf", ".txt"]), | |
| gr.Textbox(label="Ask a question about the document") | |
| ], | |
| outputs=gr.Textbox(label="Answer"), | |
| title="Document Question Answering with Gemini", | |
| description="Upload a text document (PDF or TXT) and ask questions about its content." | |
| ) | |
| # Step 11: Launch the Gradio interface with share=False for deployment | |
| if __name__ == "__main__": | |
| interface.launch(share=False) | |