Skip to content
Merged
75 changes: 45 additions & 30 deletions example/extract/extract_html.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,13 @@
{
"data": {
"text/plain": [
"{'extract': ['ExtractImageFlow',\n",
"{'extract': ['ExtractHTMLFlow',\n",
" 'ExtractImageFlow',\n",
" 'ExtractIpynbFlow',\n",
" 'ExtractMarkdownFlow',\n",
" 'ExtractPDFFlow',\n",
" 'ExtractTxtFlow',\n",
" 'ExtractS3TxtFlow',\n",
" 'ExtractHTMLFlow'],\n",
" 'ExtractS3TxtFlow'],\n",
" 'transform': ['TransformAzureOpenAIFlow',\n",
" 'TransformCopyFlow',\n",
" 'TransformHuggingFaceFlow',\n",
Expand Down Expand Up @@ -111,16 +111,16 @@
"metadata": {},
"outputs": [],
"source": [
"# data = [{\"url\": f'https://github.com/CambioML/uniflow'}]"
"data = [{\"url\": f'https://github.com/CambioML/uniflow'}]"
]
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"data = [{\"filename\": f'../transform/data/raw_input/22.11_information-theory.html'}]"
"# data = [{\"filename\": f'../transform/data/raw_input/22.11_information-theory.html'}]"
]
},
{
Expand All @@ -132,7 +132,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -141,7 +141,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"metadata": {},
"outputs": [
{
Expand All @@ -155,7 +155,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 1/1 [00:00<00:00, 4.53it/s]\n"
"100%|██████████| 1/1 [00:00<00:00, 1.91it/s]\n"
]
}
],
Expand All @@ -174,33 +174,35 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['22.11. Information Theory — Dive into Deep Learning 1.0.3 documentation22.',\n",
" 'Appendix: Mathematics for Deep Learning',\n",
" '2.1. Data Manipulation',\n",
" '2.2. Data Preprocessing',\n",
" '2.5. Automatic Differentiation',\n",
" '2.6. Probability and Statistics',\n",
" '3. Linear Neural Networks for Regression',\n",
" '3.1. Linear Regression',\n",
" '3.2. Object-Oriented Design for Implementation',\n",
" '3.3. Synthetic Regression Data',\n",
" '3.4. Linear Regression Implementation from Scratch',\n",
" '3.5. Concise Implementation of Linear Regression',\n",
" '4. Linear Neural Networks for Classification',\n",
" '4.1. Softmax Regression',\n",
" '4.2. The Image Classification Dataset',\n",
" '4.3. The Base Classification Model',\n",
" '4.4. Softmax Regression Implementation from Scratch',\n",
" '4.5. Concise Implementation of Softmax Regression',\n",
" '4.6. Generalization in Classification',\n",
" '4.7. Environment and Distribution Shift']\n"
"['GitHub - CambioML/uniflow: Unified interface for pre-training data '\n",
" 'augmentation and post-training evaluation of Large Language Models '\n",
" '(LLMs).Skip to content',\n",
" 'Automate any workflow',\n",
" 'Host and manage packages',\n",
" 'Find and fix vulnerabilities',\n",
" 'Instant dev environments',\n",
" 'Write better code with AI',\n",
" 'Collaborate outside of code',\n",
" 'White papers, Ebooks, Webinars',\n",
" 'Fund open source developers',\n",
" 'GitHub community articles',\n",
" 'Search code, repositories, users, issues, pull requests...',\n",
" 'We read every piece of feedback, and take your input very seriously.',\n",
" 'Include my email address so I can be contacted',\n",
" 'Use saved searches to filter your results more quickly',\n",
" 'To see all available qualifiers, see our',\n",
" 'You signed in with another tab or window.',\n",
" 'to refresh your session.',\n",
" 'You signed out in another tab or window.',\n",
" 'to refresh your session.',\n",
" 'You switched accounts on another tab or window.']\n"
]
}
],
Expand All @@ -209,6 +211,19 @@
"text = [p for p in text.split(\"\\n\") if len(p) > 20]\n",
"pprint.pprint(text[:20])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## End of the notebook\n",
"\n",
"Check more Uniflow use cases in the [example folder](https://github.com/CambioML/uniflow/tree/main/example/model#examples)!\n",
"\n",
"<a href=\"https://www.cambioml.com/\" title=\"Title\">\n",
" <img src=\"../image/cambioml_logo_large.png\" style=\"height: 100px; display: block; margin-left: auto; margin-right: auto;\"/>\n",
"</a>"
]
}
],
"metadata": {
Expand Down
198 changes: 198 additions & 0 deletions example/extract/extract_txt_with_recursive_splitter.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%reload_ext autoreload\n",
"%autoreload 2\n",
"\n",
"import sys\n",
"\n",
"sys.path.append(\".\")\n",
"sys.path.append(\"..\")\n",
"sys.path.append(\"../..\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/ubuntu/anaconda3/envs/uniflow/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
}
],
"source": [
"import os\n",
"import pandas as pd\n",
"from uniflow.flow.client import ExtractClient, TransformClient\n",
"from uniflow.flow.config import TransformOpenAIConfig, ExtractPDFConfig\n",
"from uniflow.op.model.model_config import OpenAIModelConfig, NougatModelConfig\n",
"from uniflow.op.prompt import PromptTemplate, Context\n",
"from uniflow.op.extract.split.splitter_factory import SplitterOpsFactory\n",
"from uniflow.op.extract.split.constants import RECURSIVE_CHARACTER_SPLITTER"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"dir_cur = os.getcwd()\n",
"pdf_file = \"1408.5882_page-1.pdf\"\n",
"input_file = os.path.join(f\"{dir_cur}/data/raw_input/\", pdf_file)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['ParagraphSplitter', 'MarkdownHeaderSplitter', 'RecursiveCharacterSplitter']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"SplitterOpsFactory.list()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/ubuntu/anaconda3/envs/uniflow/lib/python3.10/site-packages/torch/functional.py:504: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at ../aten/src/ATen/native/TensorShape.cpp:3526.)\n",
" return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]\n"
]
}
],
"source": [
"data = [\n",
" {\"filename\": input_file},\n",
"]\n",
"\n",
"config = ExtractPDFConfig(\n",
" model_config=NougatModelConfig(\n",
" model_name = \"0.1.0-small\",\n",
" batch_size = 1 # When batch_size>1, nougat will run on CUDA, otherwise it will run on CPU\n",
" ),\n",
" splitter=RECURSIVE_CHARACTER_SPLITTER,\n",
")\n",
"nougat_client = ExtractClient(config)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
" 0%| | 0/1 [00:00<?, ?it/s]"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 1/1 [00:05<00:00, 5.09s/it]\n"
]
},
{
"data": {
"text/plain": [
"[{'output': [{'text': ['# Convolutional Neural Networks for Sentence Classification Yoon KimNew York Universityyhk255@nyu.edu###### AbstractWe report on a series of experiments with convolutional neural networks (CNN) trained on top of pre-trained word vectors for sentence-level classification tasks. We show that a simple CNN with little hyperparameter tuning and static vectors achieves excellent results on multiple benchmarks. Learning task-specific vectors through fine-tuning offers further gains in performance. We additionally propose a simple modification to the architecture to allow for the use of both task-specific and static vectors. The CNN models discussed herein improve upon the state of the art on 4 out of 7 tasks, which include sentiment analysis and question classification.## 1 Introduction',\n",
" 'Deep learning models have achieved remarkable results in computer vision [11] and speech recognition [1] in recent years. Within natural language processing, much of the work with deep learning methods has involved learning word vector representations through neural language models [1, 1, 2] and performing composition over the learned word vectors for classification [1]. Word vectors, wherein words are projected from a sparse, 1-of-\\\\(V\\\\) encoding (here \\\\(V\\\\) is the vocabulary size) onto a lower dimensional vector space via a hidden layer, are essentially feature extractors that encode semantic features of words in their dimensions. In such dense representations, semantically close words are likewise close--in euclidean or cosine distance--in the lower dimensional vector space.',\n",
" 'Convolutional neural networks (CNN) utilize layers with convolving filters that are applied to local features [1]. Originally invented for computer vision, CNN models have subsequently been shown to be effective for NLP and have achieved excellent results in semantic parsing [13], search query retrieval [2], sentence modeling [1], and other traditional NLP tasks [1].',\n",
" \"In the present work, we train a simple CNN with one layer of convolution on top of word vectors obtained from an unsupervised neural language model. These vectors were trained by Mikolov et al. (2013) on 100 billion words of Google News, and are publicly available.1 We initially keep the word vectors static and learn only the other parameters of the model. Despite little tuning of hyperparameters, this simple model achieves excellent results on multiple benchmarks, suggesting that the pre-trained vectors are 'universal' feature extractors that can be utilized for various classification tasks. Learning task-specific vectors through fine-tuning results in further improvements. We finally describe a simple modification to the architecture to allow for the use of both pre-trained and task-specific vectors by having multiple channels.Footnote 1: [https://code.google.com/p/word2vec/](https://code.google.com/p/word2vec/)\",\n",
" 'Our work is philosophically similar to Razavian et al. (2014) which showed that for image classification, feature extractors obtained from a pre-trained deep learning model perform well on a variety of tasks--including tasks that are very different from the original task for which the feature extractors were trained.## 2 ModelThe model architecture, shown in figure 1, is a slight variant of the CNN architecture of Collobert et al. (2011). Let \\\\(\\\\mathbf{x}_{i}\\\\in\\\\mathbb{R}^{k}\\\\) be the \\\\(k\\\\)-dimensional word vector corresponding to the \\\\(i\\\\)-th word in the sentence. A sentence of length \\\\(n\\\\) (padded where']}],\n",
" 'root': <uniflow.node.Node at 0x7fc5fbf73af0>}]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"output = nougat_client.run(data)\n",
"output"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"contexts = output[0]['output'][0]['text']"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 # Convolutional Neural Networks for Sentence Classification Yoon KimNew York Universityyhk255@nyu.edu###### AbstractWe report on a series of experiments with convolutional neural networks (CNN) trained on top of pre-trained word vectors for sentence-level classification tasks. We show that a simple CNN with little hyperparameter tuning and static vectors achieves excellent results on multiple benchmarks. Learning task-specific vectors through fine-tuning offers further gains in performance. We additionally propose a simple modification to the architecture to allow for the use of both task-specific and static vectors. The CNN models discussed herein improve upon the state of the art on 4 out of 7 tasks, which include sentiment analysis and question classification.## 1 Introduction\n",
"1 Deep learning models have achieved remarkable results in computer vision [11] and speech recognition [1] in recent years. Within natural language processing, much of the work with deep learning methods has involved learning word vector representations through neural language models [1, 1, 2] and performing composition over the learned word vectors for classification [1]. Word vectors, wherein words are projected from a sparse, 1-of-\\(V\\) encoding (here \\(V\\) is the vocabulary size) onto a lower dimensional vector space via a hidden layer, are essentially feature extractors that encode semantic features of words in their dimensions. In such dense representations, semantically close words are likewise close--in euclidean or cosine distance--in the lower dimensional vector space.\n",
"2 Convolutional neural networks (CNN) utilize layers with convolving filters that are applied to local features [1]. Originally invented for computer vision, CNN models have subsequently been shown to be effective for NLP and have achieved excellent results in semantic parsing [13], search query retrieval [2], sentence modeling [1], and other traditional NLP tasks [1].\n",
"3 In the present work, we train a simple CNN with one layer of convolution on top of word vectors obtained from an unsupervised neural language model. These vectors were trained by Mikolov et al. (2013) on 100 billion words of Google News, and are publicly available.1 We initially keep the word vectors static and learn only the other parameters of the model. Despite little tuning of hyperparameters, this simple model achieves excellent results on multiple benchmarks, suggesting that the pre-trained vectors are 'universal' feature extractors that can be utilized for various classification tasks. Learning task-specific vectors through fine-tuning results in further improvements. We finally describe a simple modification to the architecture to allow for the use of both pre-trained and task-specific vectors by having multiple channels.Footnote 1: [https://code.google.com/p/word2vec/](https://code.google.com/p/word2vec/)\n",
"4 Our work is philosophically similar to Razavian et al. (2014) which showed that for image classification, feature extractors obtained from a pre-trained deep learning model perform well on a variety of tasks--including tasks that are very different from the original task for which the feature extractors were trained.## 2 ModelThe model architecture, shown in figure 1, is a slight variant of the CNN architecture of Collobert et al. (2011). Let \\(\\mathbf{x}_{i}\\in\\mathbb{R}^{k}\\) be the \\(k\\)-dimensional word vector corresponding to the \\(i\\)-th word in the sentence. A sentence of length \\(n\\) (padded where\n"
]
}
],
"source": [
"for i, _s in enumerate(contexts):\n",
" print(i, _s)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "uniflow",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
28 changes: 16 additions & 12 deletions uniflow/op/extract/load/html_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@
class ExtractHTMLOp(Op):
"""Extract HTML Op Class."""

def __init__(self, name: str) -> None:
try:
import requests # pylint: disable=import-outside-toplevel
from bs4 import BeautifulSoup # pylint: disable=import-outside-toplevel
except ModuleNotFoundError as exc:
raise ModuleNotFoundError(
"Please install bs4. You can use `pip install bs4` to install them."
) from exc

super().__init__(name)
self._requests_client = requests
self._beautiful_soup_parser = BeautifulSoup

def __call__(self, nodes: Sequence[Node]) -> Sequence[Node]:
"""Run Model Op.

Expand All @@ -22,9 +35,7 @@ def __call__(self, nodes: Sequence[Node]) -> Sequence[Node]:
for node in nodes:
value_dict = copy.deepcopy(node.value_dict)
if "url" in value_dict:
import requests # pylint: disable=import-outside-toplevel

resp = requests.get(url=value_dict["url"], timeout=300)
resp = self._requests_client.get(url=value_dict["url"], timeout=300)
text = resp.text
else:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we update this else to check filename and then add a else case to log regarding a specific extract format is not supported. This should help improved the readability.

with open(
Expand All @@ -43,16 +54,9 @@ def __call__(self, nodes: Sequence[Node]) -> Sequence[Node]:
)
return output_nodes

def parse_html(self, text):
def parse_html(self, text) -> str:
"""Function Parse Html."""
try:
from bs4 import BeautifulSoup # pylint: disable=import-outside-toplevel
except ModuleNotFoundError as exc:
raise ModuleNotFoundError(
"Please install bs4. You can use `pip install bs4` to install them."
) from exc

soup = BeautifulSoup(text, "html.parser")
soup = self._beautiful_soup_parser(text, "html.parser")

if soup.title:
title = str(soup.title.string)
Expand Down
Loading