Marroco93 commited on
Commit
10d17a3
1 Parent(s): abb61e1

no message

Browse files
Files changed (1) hide show
  1. main.py +78 -134
main.py CHANGED
@@ -11,8 +11,9 @@ import nltk
11
  import os
12
  import google.protobuf # This line should execute without errors if protobuf is installed correctly
13
  import sentencepiece
14
- from transformers import pipeline, AutoTokenizer,AutoModelForSequenceClassification
15
  import spacy
 
16
 
17
 
18
  nltk.data.path.append(os.getenv('NLTK_DATA'))
@@ -80,7 +81,6 @@ async def generate_text(item: Item):
80
  return StreamingResponse(generate_stream(item), media_type="application/x-ndjson")
81
 
82
 
83
-
84
  # Load spaCy model
85
  nlp = spacy.load("en_core_web_sm")
86
 
@@ -93,152 +93,96 @@ def preprocess_text(text: str) -> str:
93
  text = re.sub(r'[^\w\s]', '', text)
94
  return text
95
 
96
- def reduce_tokens(text: str):
97
- # Process the text with spaCy
98
- doc = nlp(text)
99
- # Select sentences that might be more important - this is a simple heuristic
100
- important_sentences = []
101
- for sent in doc.sents:
102
- if any(tok.dep_ == 'ROOT' for tok in sent):
103
- important_sentences.append(sent.text)
104
- # Join selected sentences to form the reduced text
105
- reduced_text = ' '.join(important_sentences)
106
- # Tokenize the reduced text to count the tokens
107
- reduced_doc = nlp(reduced_text) # Ensure this line is correctly aligned
108
- token_count = len(reduced_doc)
109
- return reduced_text, token_count
110
-
111
- def segment_text(text: str, max_tokens=500): # Setting a conservative limit below 512
112
- doc = nlp(text)
113
- segments = []
114
- current_segment = []
115
- current_length = 0
116
-
117
- for sent in doc.sents:
118
- sentence = sent.text.strip()
119
- sentence_length = len(sentence.split()) # Counting words for simplicity
120
-
121
- if sentence_length > max_tokens:
122
- # Split long sentences into smaller chunks if a single sentence exceeds max_tokens
123
- words = sentence.split()
124
- while words:
125
- part = ' '.join(words[:max_tokens])
126
- segments.append(part)
127
- words = words[max_tokens:]
128
- elif current_length + sentence_length > max_tokens:
129
- segments.append(' '.join(current_segment))
130
- current_segment = [sentence]
131
- current_length = sentence_length
132
- else:
133
- current_segment.append(sentence)
134
- current_length += sentence_length
135
-
136
- if current_segment: # Add the last segment
137
- segments.append(' '.join(current_segment))
138
-
139
- return segments
140
-
141
-
142
- # Load the tokenizer and model
143
- tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
144
- model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
145
-
146
- # Set up the pipeline
147
- classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
148
-
149
- def robust_segment_text(text: str, max_tokens=510):
150
- doc = nlp(text)
151
- segments = []
152
- current_segment = []
153
- current_tokens = []
154
-
155
- for sent in doc.sents:
156
- words = sent.text.strip().split()
157
- sentence_tokens = tokenizer.encode(' '.join(words), add_special_tokens=False)
158
-
159
- if len(current_tokens) + len(sentence_tokens) > max_tokens:
160
- segments.append(tokenizer.decode(current_tokens))
161
- current_segment = words
162
- current_tokens = sentence_tokens
163
- else:
164
- current_segment.extend(words)
165
- current_tokens.extend(sentence_tokens)
166
-
167
- if current_tokens: # Add the last segment
168
- segments.append(tokenizer.decode(current_tokens))
169
-
170
- return segments
171
-
172
-
173
- def classify_segments(segments):
174
- labels = [
175
- "Coverage Details", "Exclusions", "Premiums", "Claims Process",
176
- "Policy Limits", "Legal and Regulatory Information", "Renewals and Cancellations",
177
- "Discounts and Incentives", "Duties and Responsibilities", "Contact Information"
178
- ]
179
- classified_segments = []
180
- for segment in segments:
181
- # Note: Adjust the input here based on how your model was trained
182
- predictions = classifier(segment)
183
- classified_segments.append(predictions)
184
- return classified_segments
185
 
 
 
186
 
 
187
 
 
 
 
188
 
189
- class TextRequest(BaseModel):
190
- text: str
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  @app.post("/process_document")
193
  async def process_document(request: TextRequest):
194
  try:
195
- processed_text = preprocess_text(request.text) # Ensure preprocess_text is defined
196
- segments = robust_segment_text(processed_text)
197
- classified_segments = classify_segments(segments)
198
 
199
  return {
200
- "classified_segments": classified_segments
 
201
  }
202
  except Exception as e:
203
  print(f"Error during document processing: {e}")
204
  raise HTTPException(status_code=500, detail=str(e))
205
 
206
-
207
- @app.post("/summarize")
208
- async def summarize(request: TextRequest):
209
- try:
210
- # Preprocess and segment the text
211
- processed_text = preprocess_text(request.text)
212
- segments = segment_text(processed_text)
213
-
214
- # Classify each segment safely
215
- classified_segments = []
216
- for segment in segments:
217
- try:
218
- result = classifier(segment)
219
- classified_segments.append(result)
220
- except Exception as e:
221
- print(f"Error classifying segment: {e}")
222
- classified_segments.append({"error": str(e)})
223
-
224
- # Optional: Reduce tokens or summarize
225
- reduced_texts = []
226
- for segment in segments:
227
- try:
228
- reduced_text, token_count = reduce_tokens(segment)
229
- reduced_texts.append((reduced_text, token_count))
230
- except Exception as e:
231
- print(f"Error during token reduction: {e}")
232
- reduced_texts.append(("Error", 0))
233
-
234
- return {
235
- "classified_segments": classified_segments,
236
- "reduced_texts": reduced_texts
237
- }
238
 
239
- except Exception as e:
240
- print(f"Error during token reduction: {e}")
241
- raise HTTPException(status_code=500, detail=str(e))
242
 
243
- if __name__ == "__main__":
244
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
11
  import os
12
  import google.protobuf # This line should execute without errors if protobuf is installed correctly
13
  import sentencepiece
14
+ from transformers import pipeline, AutoTokenizer,AutoModelForSequenceClassification,AutoModel
15
  import spacy
16
+ import numpy as np
17
 
18
 
19
  nltk.data.path.append(os.getenv('NLTK_DATA'))
 
81
  return StreamingResponse(generate_stream(item), media_type="application/x-ndjson")
82
 
83
 
 
84
  # Load spaCy model
85
  nlp = spacy.load("en_core_web_sm")
86
 
 
93
  text = re.sub(r'[^\w\s]', '', text)
94
  return text
95
 
96
+ def embed_text(text: str) -> np.ndarray:
97
+ # Load the JinaAI/jina-embeddings-v2-base-en model
98
+ model_name = "JinaAI/jina-embeddings-v2-base-en"
99
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
100
+ model = AutoModel.from_pretrained(model_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ inputs = tokenizer(text, return_tensors='pt')
103
+ embeddings = model(**inputs).pooler_output.numpy()
104
 
105
+ return embeddings
106
 
107
+ def semantic_matching(text, context):
108
+ text_embeddings = embed_text(text)
109
+ context_embeddings = [embed_text(ctx) for ctx in context]
110
 
111
+ # Calculate cosine similarity between text and context embeddings
112
+ similarities = np.dot(text_embeddings, context_embeddings.T)
113
+
114
+ # Find the most similar sentence in the context
115
+ most_similar_idx = np.argmax(similarities)
116
+
117
+ return context[most_similar_idx]
118
+
119
+ def handle_endpoint(text):
120
+ # Define your large context here
121
+ context = [
122
+ "This is a sample context sentence 1.",
123
+ "Another context sentence to provide additional information.",
124
+ "This context sentence introduces a new topic.",
125
+ "Some additional details about the new topic are provided here.",
126
+ "Context sentences can be added or removed as needed.",
127
+ "The context should cover a range of topics and provide relevant information.",
128
+ "Make sure the context is diverse and representative of the domain.",
129
+ ]
130
+
131
+ # Perform semantic matching to retrieve the most relevant portion of the context
132
+ relevant_context = semantic_matching(text, context)
133
+
134
+ return relevant_context
135
 
136
  @app.post("/process_document")
137
  async def process_document(request: TextRequest):
138
  try:
139
+ processed_text = preprocess_text(request.text)
140
+ embedded_text = embed_text(processed_text)
141
+ relevant_context = handle_endpoint(processed_text)
142
 
143
  return {
144
+ "embedded_text": embedded_text.tolist(),
145
+ "relevant_context": relevant_context
146
  }
147
  except Exception as e:
148
  print(f"Error during document processing: {e}")
149
  raise HTTPException(status_code=500, detail=str(e))
150
 
151
+ # @app.post("/summarize")
152
+ # async def summarize(request: TextRequest):
153
+ # try:
154
+ # # Preprocess and segment the text
155
+ # processed_text = preprocess_text(request.text)
156
+ # segments = segment_text(processed_text)
157
+
158
+ # # Classify each segment safely
159
+ # classified_segments = []
160
+ # for segment in segments:
161
+ # try:
162
+ # result = classifier(segment)
163
+ # classified_segments.append(result)
164
+ # except Exception as e:
165
+ # print(f"Error classifying segment: {e}")
166
+ # classified_segments.append({"error": str(e)})
167
+
168
+ # # Optional: Reduce tokens or summarize
169
+ # reduced_texts = []
170
+ # for segment in segments:
171
+ # try:
172
+ # reduced_text, token_count = reduce_tokens(segment)
173
+ # reduced_texts.append((reduced_text, token_count))
174
+ # except Exception as e:
175
+ # print(f"Error during token reduction: {e}")
176
+ # reduced_texts.append(("Error", 0))
177
+
178
+ # return {
179
+ # "classified_segments": classified_segments,
180
+ # "reduced_texts": reduced_texts
181
+ # }
 
182
 
183
+ # except Exception as e:
184
+ # print(f"Error during token reduction: {e}")
185
+ # raise HTTPException(status_code=500, detail=str(e))
186
 
187
+ # if __name__ == "__main__":
188
+ # uvicorn.run(app, host="0.0.0.0", port=8000)