mattoofahaddcube commited on
Commit
ef1dd9e
β€’
0 Parent(s):

Initial commit

Browse files
Files changed (8) hide show
  1. .github/workflows/hf-space.yml +19 -0
  2. .gitignore +164 -0
  3. Dockerfile +23 -0
  4. README.md +95 -0
  5. config.py +7 -0
  6. logs.py +96 -0
  7. main.py +34 -0
  8. requirements.txt +6 -0
.github/workflows/hf-space.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ # to run this workflow manually from the Actions tab
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ sync-to-hub:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ with:
14
+ fetch-depth: 0
15
+ lfs: true
16
+ - name: Push to hub
17
+ env:
18
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
19
+ run: git push https://mattoofahad:$HF_TOKEN@huggingface.co/spaces/mattoofahad/whatsapp-endpoint main
.gitignore ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+
164
+ ngrok.exe
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11
2
+
3
+ # Create a user and switch to it
4
+ RUN useradd -m -u 1000 user
5
+ USER user
6
+ ENV PATH="/home/user/.local/bin:$PATH"
7
+
8
+ # Set the working directory
9
+ WORKDIR /app
10
+
11
+ # Copy and install dependencies
12
+ COPY --chown=user ./requirements.txt /app/requirements.txt
13
+ RUN pip install --upgrade pip
14
+ RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
15
+
16
+ # Copy application files
17
+ COPY --chown=user . /app/
18
+
19
+ # Expose the port
20
+ EXPOSE 7860
21
+
22
+ # Use CMD or ENTRYPOINT
23
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: This a fastapi endpoint for whatsapp chat.
3
+ colorFrom: red
4
+ colorTo: green
5
+ emoji: πŸ‘ŒπŸ‘Œ
6
+ sdk: docker
7
+ app_file: main.py
8
+ pinned: false
9
+ ---
10
+
11
+ # Whatsapp-Chatbot
12
+ A simple repository to integrate a chatbot with whatsapp.
13
+
14
+ <!-- <p float="left">
15
+ <img src="" alt="screenshot1" width="300" style="margin-right: 20px;" />
16
+ <img src="" alt="screenshot2" width="300" />
17
+ </p> -->
18
+
19
+ <!-- ## Purpose and Features ✨ -->
20
+
21
+
22
+ <!-- ## Prerequisites πŸ”‘
23
+
24
+ To run and deploy the WhatsApp chatbot, you will need the following:
25
+
26
+ 1. [Twilio Account](https://console.twilio.com/user/account-create): Create a Twilio account and obtain your Account SID and Auth Token.
27
+
28
+ 2. WhatsApp Sandbox: Set up a WhatsApp Sandbox in your Twilio account to receive and send messages.
29
+
30
+ 3. Python: Install Python on your local machine. The recommended version is Python 3.x.
31
+
32
+ 4. Ngrok: [Download](https://ngrok.com/download) and install Ngrok from the official website (https://ngrok.com/) based on your operating system.
33
+
34
+ 5. OpenAI API: Sign up for the OpenAI API and obtain your Secret API key from user settings (you may require a paid account for this). -->
35
+
36
+ ## Installation and Usage πŸš€πŸ’»
37
+
38
+ 1. Create conda env
39
+ ```bash
40
+ conda create -n whatsapp_bot_env python=3.10 -y
41
+ ```
42
+
43
+ 2. Activate env
44
+ ```bash
45
+ conda activate whatsapp_bot_env
46
+ ```
47
+
48
+ 3. Install the required Python packages:
49
+
50
+ ```bash
51
+ pip install -r requirements.txt
52
+ ```
53
+
54
+ # docker
55
+
56
+ ## Docker
57
+ 1. Create the docker container
58
+ ```bash
59
+ docker build -t whatapp-endpoint .
60
+ ```
61
+
62
+ 2. run the container
63
+ ```bash
64
+ docker run -p 7860:7860 whatapp-endpoint
65
+ ```
66
+ <!-- 4. Create a `.env` file in the root directory of the project. -->
67
+
68
+ <!-- 5. Add the following lines to the `.env` file:
69
+
70
+ ```plaintext
71
+ TWILIO_ACCOUNT_SID=your_account_sid
72
+ TWILIO_AUTH_TOKEN=your_auth_token
73
+ OPENAI_API_KEY=your_openai_api_key
74
+ TWILIO_NUMBER= your_twilio_number
75
+ RECEIPENT_NUMBER= your_number
76
+ ```
77
+
78
+ Replace `your_account_sid`, `your_auth_token`, `your_openai_api_key`, `your_twilio_number`, and `your_number` with your actual credentials. -->
79
+
80
+
81
+ 5. Run the local server:
82
+
83
+ ```bash
84
+ uvicorn main:app --host 0.0.0.0 --port 5000
85
+ ```
86
+
87
+ <!-- 6. Start Ngrok to create a public URL for your local server:
88
+
89
+ ```bash
90
+ ngrok http 5000
91
+ ```
92
+
93
+ 7. Update the WhatsApp sandbox with the Ngrok URL. Set the incoming message webhook to `<your_ngrok_url>/message` , leave the callback url box empty.
94
+
95
+ 8. Send a message to the WhatsApp sandbox number to interact with the bot and receive information. -->
config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from dotenv import find_dotenv, load_dotenv
4
+
5
+ load_dotenv(find_dotenv(), override=True)
6
+
7
+ LOGGER_LEVEL = os.getenv("LOGGER_LEVEL")
logs.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import sys
4
+ import time
5
+ from functools import wraps
6
+
7
+ from colorama import Back, Fore, Style, init
8
+
9
+ from config import LOGGER_LEVEL
10
+
11
+ # Initialize colorama
12
+ init(autoreset=True)
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ if not logger.hasHandlers():
17
+ logger.propagate = False
18
+ logger.setLevel(LOGGER_LEVEL)
19
+
20
+ # Define color codes for different log levels
21
+ log_colors = {
22
+ logging.DEBUG: Fore.CYAN,
23
+ logging.INFO: Fore.GREEN,
24
+ logging.WARNING: Fore.YELLOW,
25
+ logging.ERROR: Fore.RED,
26
+ logging.CRITICAL: Fore.RED + Back.WHITE + Style.BRIGHT,
27
+ }
28
+
29
+ class ColoredFormatter(logging.Formatter):
30
+ """Module doc string"""
31
+
32
+ def format(self, record):
33
+ """Module doc string"""
34
+
35
+ levelno = record.levelno
36
+ color = log_colors.get(levelno, "")
37
+
38
+ # Format the message
39
+ message = record.getMessage()
40
+
41
+ # Format the rest of the log details
42
+ details = self._fmt % {
43
+ "asctime": self.formatTime(record, self.datefmt),
44
+ "levelname": record.levelname,
45
+ "module": record.module,
46
+ "funcName": record.funcName,
47
+ "lineno": record.lineno,
48
+ }
49
+
50
+ # Combine details and colored message
51
+ return f"{Fore.WHITE}{details} :: {color}{message}{Style.RESET_ALL}"
52
+
53
+ normal_handler = logging.StreamHandler(sys.stdout)
54
+ normal_handler.setLevel(logging.DEBUG)
55
+ normal_handler.addFilter(lambda logRecord: logRecord.levelno < logging.WARNING)
56
+
57
+ error_handler = logging.StreamHandler(sys.stderr)
58
+ error_handler.setLevel(logging.WARNING)
59
+
60
+ formatter = ColoredFormatter(
61
+ "%(asctime)s :: %(levelname)s :: %(module)s :: %(funcName)s :: %(lineno)d"
62
+ )
63
+
64
+ normal_handler.setFormatter(formatter)
65
+ error_handler.setFormatter(formatter)
66
+
67
+ logger.addHandler(normal_handler)
68
+ logger.addHandler(error_handler)
69
+
70
+
71
+ def log_execution_time(func):
72
+ """Module doc string"""
73
+
74
+ @wraps(func)
75
+ def sync_wrapper(*args, **kwargs):
76
+ start_time = time.time()
77
+ result = func(*args, **kwargs)
78
+ end_time = time.time()
79
+ execution_time = end_time - start_time
80
+ message_string = f"{func.__name__} executed in {execution_time:.4f} seconds"
81
+ logger.debug(message_string)
82
+ return result
83
+
84
+ @wraps(func)
85
+ async def async_wrapper(*args, **kwargs):
86
+ start_time = time.time()
87
+ result = await func(*args, **kwargs)
88
+ end_time = time.time()
89
+ execution_time = end_time - start_time
90
+ message_string = f"{func.__name__} executed in {execution_time:.4f} seconds"
91
+ logger.debug(message_string)
92
+ return result
93
+
94
+ if asyncio.iscoroutinefunction(func):
95
+ return async_wrapper
96
+ return sync_wrapper
main.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from fastapi import FastAPI, Request
3
+ from fastapi.responses import PlainTextResponse
4
+ from pydantic import BaseModel
5
+
6
+ from logs import logger, log_execution_time
7
+
8
+ app = FastAPI()
9
+
10
+
11
+ class UserInputModel(BaseModel):
12
+ user_input: str
13
+
14
+
15
+ @log_execution_time
16
+ @app.post("/message")
17
+ async def twilio_message_endpoint(request: Request):
18
+ data = await request.form()
19
+ user_input = data.get("Body", "")
20
+ user_input = data.user_input
21
+ reqUrl = "https://mattoofahad-whatsapp-endpoint.hf.space/message"
22
+ headersList = {
23
+ "Accept": "*/*",
24
+ "User-Agent": "Thunder Client (https://www.thunderclient.com)",
25
+ "Content-Type": "application/x-www-form-urlencoded",
26
+ }
27
+ payload = f"Body={user_input}"
28
+ response = requests.request("POST", reqUrl, data=payload, headers=headersList)
29
+ logger.info(response.text)
30
+ return PlainTextResponse(response.text)
31
+
32
+
33
+ if __name__ == "__main__":
34
+ app.run()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.111.1
2
+ uvicorn==0.30.1
3
+ twilio==8.2.2
4
+ openai==1.40.6
5
+ python-dotenv==1.0.1
6
+ colorama==0.4.6