ZacBl commited on
Commit
9442f80
·
verified ·
1 Parent(s): 9ff2eb6

Update doc_preprocessing.py

Browse files
Files changed (1) hide show
  1. doc_preprocessing.py +41 -84
doc_preprocessing.py CHANGED
@@ -1,70 +1,3 @@
1
- # from pypdf import PdfReader
2
- # import docx
3
- # from transformers.pipelines import pipeline
4
- # import streamlit as st
5
-
6
- # def extract_text(file):
7
- # text = ""
8
- # if file.name.endswith(".pdf"):
9
- # try:
10
- # reader = PdfReader(file)
11
- # for page in reader.pages:
12
- # text += page.extract_text() + "\n"
13
- # except Exception as e:
14
- # st.error(f"Error reading PDF {file.name}: {e}")
15
- # return ""
16
- # elif file.name.endswith(".docx"):
17
- # try:
18
- # document = docx.Document(file)
19
- # for paragraph in document.paragraphs:
20
- # text += paragraph.text + "\n"
21
- # except Exception as e:
22
- # st.error(f"Error reading DOCX {file.name}: {e}")
23
- # return ""
24
- # return text
25
-
26
- # def chunk_text(text, chunk_size=500, overlap=50):
27
- # chunks = []
28
- # start = 0
29
- # while start < len(text):
30
- # end = start + chunk_size
31
- # chunk = text[start:end]
32
- # chunks.append(chunk)
33
- # start = end - overlap
34
- # return chunks
35
-
36
- # def get_embeddings(texts):
37
- # try:
38
- # embedding_model = pipeline(
39
- # 'document-question-answering',
40
- # "sentence-transformers/all-MiniLM-L6-v2"
41
- # ) # Example model
42
- # embeddings = embedding_model(texts)
43
- # return embeddings
44
- # except Exception as e:
45
- # st.error(f"Error generating embeddings: {e}")
46
- # return []
47
-
48
- # def process_files(files):
49
- # all_chunks = []
50
- # all_embeddings = []
51
- # chunks_metadata = []
52
-
53
- # for file in files:
54
- # text = extract_text(file)
55
- # if not text: # Skip files that failed to process
56
- # continue
57
- # chunks = chunk_text(text)
58
- # embeddings = get_embeddings(chunks)
59
- # if not embeddings: # Skip files that failed to embed
60
- # continue
61
-
62
- # all_chunks.extend(chunks)
63
- # all_embeddings.extend(embeddings)
64
- # for i, chunk in enumerate(chunks):
65
- # chunks_metadata.append({"file_name": file.name, "chunk_index": i})
66
- # print(f"Processed {len(files)} files, {len(all_chunks)} chunks generated.")
67
- # return all_chunks, all_embeddings, chunks_metadata
68
  import pypdf
69
  from docx import Document
70
  from transformers.pipelines import pipeline
@@ -140,26 +73,50 @@ def get_embeddings(texts)-> np.ndarray:
140
  st.error(f"Error generating embeddings: {e}")
141
  return []
142
 
143
- def process_files(files):
144
  all_chunks = []
145
  all_embeddings = []
146
  chunks_metadata = []
147
 
148
- for file in files:
149
- print(f"Processing file: {file.name if hasattr(file, 'name') else os.path.basename(file)}")
150
- text = extract_text(file)
151
- if not text: # Skip files that failed to process
152
- print(f"Skipping file {file.name if hasattr(file, 'name') else os.path.basename(file)} due to extraction error.")
153
- continue
154
- print(f"Chunking text...{file.name if hasattr(file, 'name') else os.path.basename(file)}\n")
155
- chunks = chunk_text(text)
156
- embeddings = get_embeddings(chunks)
157
- # if not embeddings: # Skip files that failed to embed
158
- # continue
159
 
160
- all_chunks.extend(chunks)
161
- all_embeddings.extend(embeddings)
162
- for i, chunk in enumerate(chunks):
163
- chunks_metadata.append({"file_name": file.name if hasattr(file, 'name') else os.path.basename(file), "chunk_index": i})
164
- return all_chunks, all_embeddings, chunks_metadata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pypdf
2
  from docx import Document
3
  from transformers.pipelines import pipeline
 
73
  st.error(f"Error generating embeddings: {e}")
74
  return []
75
 
76
+ def process_files(uploaded_files):
77
  all_chunks = []
78
  all_embeddings = []
79
  chunks_metadata = []
80
 
81
+ for uploaded_file in uploaded_files:
82
+ # Create a temporary file within a writable directory
83
+ # Hugging Face Spaces usually allows writing to /tmp/ or your app's directory
84
+ with tempfile.NamedTemporaryFile(delete=False, suffix=f".{uploaded_file.type.split('/')[-1]}") as temp_file:
85
+ temp_file.write(uploaded_file.getvalue())
86
+ temp_file_path = temp_file.name
 
 
 
 
 
87
 
88
+ try:
89
+ # Now, use temp_file_path to process the file
90
+ # Your existing process_files logic would go here,
91
+ # reading from temp_file_path
92
+ st.write(f"Processing file: {temp_file_path}")
93
+ # Example: Replace this with your actual processing logic
94
+ # For PDF/Word, you'd likely use a library like pypdf, python-docx, or langchain loaders
95
+ if uploaded_file.type == "application/pdf":
96
+ # Example for PDF:
97
+ # from pypdf import PdfReader
98
+ # reader = PdfReader(temp_file_path)
99
+ # text = ""
100
+ # for page in reader.pages:
101
+ # text += page.extract_text() + "\n"
102
+ pass # Replace with actual PDF processing
103
+ elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
104
+ # Example for DOCX:
105
+ # from docx import Document
106
+ # document = Document(temp_file_path)
107
+ # text = ""
108
+ # for paragraph in document.paragraphs:
109
+ # text += paragraph.text + "\n"
110
+ pass # Replace with actual DOCX processing
111
+
112
+ # Placeholder for chunking, embedding, and metadata extraction
113
+ # (You'd replace this with your actual logic based on the processed file content)
114
+ all_chunks.append(f"Content from {uploaded_file.name}")
115
+ all_embeddings.append([0.1, 0.2, 0.3]) # Replace with actual embeddings
116
+ chunks_metadata.append({"filename": uploaded_file.name})
117
+
118
+ finally:
119
+ # Clean up the temporary file
120
+ os.remove(temp_file_path)
121
 
122
+ return all_chunks, all_embeddings, chunks_metadata