Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Facebook Messanger data loader integration #16048

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
llama_index/_static
.DS_Store
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
bin/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
etc/
include/
lib/
lib64/
parts/
sdist/
share/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
.ruff_cache

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints
notebooks/

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pyvenv.cfg

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# Jetbrains
.idea
modules/
*.swp

# VsCode
.vscode

# pipenv
Pipfile
Pipfile.lock

# pyright
pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
poetry_requirements(
name="poetry",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
GIT_ROOT ?= $(shell git rev-parse --show-toplevel)

help: ## Show all Makefile targets.
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[33m%-30s\033[0m %s\n", $$1, $$2}'

format: ## Run code autoformatters (black).
pre-commit install
git ls-files | xargs pre-commit run black --files

lint: ## Run linters: pre-commit (black, ruff, codespell) and mypy
pre-commit install && git ls-files | xargs pre-commit run --show-diff-on-failure --files

test: ## Run tests via pytest.
pytest tests

watch-docs: ## Build and watch documentation.
sphinx-autobuild docs/ docs/_build/html --open-browser --watch $(GIT_ROOT)/llama_index/
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# LlamaIndex Readers Integration: Facebook_Messanger
# Messanger chat loader

```bash
pip install llama-index-readers-messenger
```

## Export a Facebook Messanger chat

1. Go to Facebook's Download Your Information (https://www.facebook.com/login.php?next=https%3A%2F%2Fwww.facebook.com%2Fdyi%2F) page.
2. Select Messages and click on Request a download.
3. Once the file is ready, download the file and unzip it.
4. Find the chat you want to analyze in the messages folder, typically in .json format.
5. Save the .json file in your working directory.

For more info see [Meta's Help Center](https://www.facebook.com/help/1701730696756992/)

## Usage

- Messages will get saved in the format: `{timestamp} {author}: {message}`.This is helpful when analyzing conversations, particularly in group chats, and allows filtering based on users, dates, or keywords.
- Metadata automatically included: `source` (file name), `author` and `timestamp`.

```python
from pathlib import Path

from llama_index.readers.messenger import FacebookMessengerLoader

path = "facebook_chat.json"
loader = FacebookMessengerLoader(path=path)
documents = loader.load_data()

# see what's created
documents[0]
# >>> Document(text='2023-02-20 00:00:00 Jane Doe: Hello, how are you?', doc_id='b7a2d508-3ba2-42e1-a3bc-8bf235232364', embedding=None, extra_info={'source': 'Facebook Chat with Jane Doe', 'author': 'Jane Doe', 'timestamp': '2023-02-20 00:00:00'})
```

This loader is designed to be used as a way to load Facebook Messenger data into https://github.com/run-llama/llama_index/
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python_sources()
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from llama_index.readers.facebook_messanger.base import FacebookMessengerLoader


__all__ = ["<FacebookMessengerLoader>"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import logging
from pathlib import Path
from typing import List

from llama_index.core.readers.base import BaseReader
from llama_index.core.schema import Document


class FacebookMessengerLoader(BaseReader):
"""
Facebook Messenger chat data loader.

Args:
path (str): Path to Facebook Messenger chat file.
"""

def __init__(self, path: str):
"""Initialize with path."""
self.file_path = path

def load_data(self) -> List[Document]:
"""
Parse Facebook Messenger file into Documents.
"""
import json

path = Path(self.file_path)

# Load the Facebook Messenger chat data
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)

logging.debug(f"> Number of messages: {len(data['messages'])}.")

docs = []
n = 0

# Parsing through messages
for message in data["messages"]:
# Check for required fields in message
author = message.get("sender_name", "Unknown")
timestamp = message.get("timestamp_ms", "")
text = message.get("content", "")

extra_info = {
"source": str(path).split("/")[-1].replace(".json", ""),
"author": author,
"timestamp": str(timestamp),
}

docs.append(
Document(
text=str(timestamp) + " " + author + ": " + text,
extra_info=extra_info,
)
)

n += 1
logging.debug(f"Added {n} of {len(data['messages'])} messages.")

logging.debug(f"> Document creation for {path} is complete.")
return docs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.codespell]
check-filenames = true
check-hidden = true
# Feel free to un-skip examples, and experimental, you will just need to
# work through many typos (--write-changes and --interactive will help)
skip = "*.csv,*.html,*.json,*.jsonl,*.pdf,*.txt,*.ipynb"

# [tool.llamahub]
# contains_example = false
# import_path = "llama_index.readers.facebook_messanger"

# [tool.llamahub.class_authors]
# FacebookMessengerLoader = "Shailesh-05"

[tool.mypy]
disallow_untyped_defs = true
# Remove venv skip when integrated with pre-commit
exclude = ["_static", "build", "examples", "notebooks", "venv"]
ignore_missing_imports = true
python_version = "3.8"

[tool.poetry]
name = "llama-index-readers-facebook-messanger"
version = "0.1.0"
description = "llama-index readers facebook_messanger integration"
authors = ["Your Name <[email protected]>"]
license = "MIT"
readme = "README.md"
maintainers = ["Shailesh-05"]
packages = [{include = "llama_index/"}]

[tool.poetry.dependencies]
python = ">=3.8.1,<4.0"
llama-index-core = "^0.10.0"

[tool.poetry.group.dev.dependencies]
black = {extras = ["jupyter"], version = "<=23.9.1,>=23.7.0"}
codespell = {extras = ["toml"], version = ">=v2.2.6"}
ipython = "8.10.0"
jupyter = "^1.0.0"
mypy = "0.991"
pre-commit = "3.2.0"
pylint = "2.15.10"
pytest = "7.2.1"
pytest-mock = "3.11.1"
ruff = "0.0.292"
tree-sitter-languages = "^1.8.0"
types-Deprecated = ">=0.1.0"
types-PyYAML = "^6.0.12.12"
types-protobuf = "^4.24.0.4"
types-redis = "4.5.5.0"
types-requests = "2.28.11.8" # TODO: unpin when mypy>0.991
types-setuptools = "67.1.0.0"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
python_tests(
interpreter_constraints=["==3.8.*","==3.9.*", "==3.10.*","==3.11.*"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from llama_index.core.readers.base import BaseReader
from llama_index.readers.facebook_messanger import FacebookMessengerLoader


def test_class():
names_of_base_classes = [b.__name__ for b in FacebookMessengerLoader.__mro__]
assert BaseReader.__name__ in names_of_base_classes
Loading