Skip to content

Commit

Permalink
Merge pull request #115 from revanth1718/main
Browse files Browse the repository at this point in the history
Streamlit App for Depression Support  Issue no #99
  • Loading branch information
TAHIR0110 authored May 28, 2024
2 parents a0c5fc1 + e415bc6 commit 1a2534c
Show file tree
Hide file tree
Showing 1,503 changed files with 277,910 additions and 0 deletions.
Binary file added chatbot_app/__pycache__/chatbot.cpython-311.pyc
Binary file not shown.
96 changes: 96 additions & 0 deletions chatbot_app/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import streamlit as st
from dataclasses import dataclass
from typing import Literal
import streamlit.components.v1 as components
from chatbot import ai_chatbot, load_dataset

@dataclass
class Message:
"""Class for keeping track of a chat message."""
origin: Literal["human", "ai"]
message: str

def load_css():
with open("styles.css") as f:
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

def initialize_session_state():
if "history" not in st.session_state:
st.session_state.history = []
if "dataset" not in st.session_state:
st.session_state.dataset = load_dataset('therapy_dataset.csv')

def on_click_callback():
user_prompt = st.session_state.human_prompt
if user_prompt.lower() in ["hello", "hello bot"]:
response = "Hello! How are you feeling today? Please tell me more about your feelings."
else:
response = ai_chatbot(user_prompt, st.session_state.dataset)
if response is None:
response = "I'm sorry, I don't understand. Can you please rephrase or provide more information?"
st.session_state.history.append(Message("human", user_prompt))
st.session_state.history.append(Message("ai", response))

load_css()
initialize_session_state()

st.title("Depression Support Chatbot 🤖")

chat_placeholder = st.container()
prompt_placeholder = st.form("chat-form")

with chat_placeholder:
for chat in st.session_state.history:
icon = "🤖" if chat.origin == 'ai' else "👤"
div = f"""
<div class="chat-row
{'' if chat.origin == 'ai' else 'row-reverse'}">
<div class="chat-icon">{icon}</div>
<div class="chat-bubble {'ai-bubble' if chat.origin == 'ai' else 'human-bubble'}">
&#8203;{chat.message}
</div>
</div>
"""
st.markdown(div, unsafe_allow_html=True)

for _ in range(3):
st.markdown("")

with prompt_placeholder:
st.markdown("**Chat**")
cols = st.columns((7, 1))
cols[0].text_input(
"Chat",
value="Hello bot",
label_visibility="collapsed",
key="human_prompt",
)
cols[1].form_submit_button(
"Submit",
type="primary",
on_click=on_click_callback,
)

components.html("""
<script>
const streamlitDoc = window.parent.document;
const buttons = Array.from(
streamlitDoc.querySelectorAll('.stButton > button')
);
const submitButton = buttons.find(
el => el.innerText === 'Submit'
);
streamlitDoc.addEventListener('keydown', function(e) {
switch (e.key) {
case 'Enter':
submitButton.click();
break;
}
});
</script>
""",
height=0,
width=0,
)
51 changes: 51 additions & 0 deletions chatbot_app/chatbot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

import spacy
import csv


nlp = spacy.load("en_core_web_sm")

memory = []

def load_dataset(file_path):
dataset = []
with open(file_path, mode='r', encoding='utf-8') as file:
csv_reader = csv.reader(file)
next(csv_reader)
for row in csv_reader:
if len(row) >= 2:
dataset.append((row[0], row[1]))
return dataset

def find_closest_prompt(user_input, dataset):
input_doc = nlp(user_input)
closest_prompt = None
min_similarity = 0

for prompt, _ in dataset:
prompt_doc = nlp(prompt)
similarity = input_doc.similarity(prompt_doc)
if similarity > min_similarity:
min_similarity = similarity
closest_prompt = prompt

return closest_prompt

def get_response(user_input, dataset):
closest_prompt = find_closest_prompt(user_input, dataset)

if closest_prompt is None:
return "I'm sorry, I don't understand. Can you please rephrase or provide more information?"

for prompt, response in dataset:
if prompt == closest_prompt:
return response

def ai_chatbot(user_input, dataset):
global memory
if 'hello' in user_input.lower():
response = "Hello! How are you feeling today? Please tell me more about your feelings."
else:
response = get_response(user_input, dataset)
memory.append((user_input, response))
return response
222 changes: 222 additions & 0 deletions chatbot_app/chatbot_env/Lib/site-packages/_distutils_hack/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
# don't import any costly modules
import sys
import os


is_pypy = '__pypy__' in sys.builtin_module_names


def warn_distutils_present():
if 'distutils' not in sys.modules:
return
if is_pypy and sys.version_info < (3, 7):
# PyPy for 3.6 unconditionally imports distutils, so bypass the warning
# https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
return
import warnings

warnings.warn(
"Distutils was imported before Setuptools, but importing Setuptools "
"also replaces the `distutils` module in `sys.modules`. This may lead "
"to undesirable behaviors or errors. To avoid these issues, avoid "
"using distutils directly, ensure that setuptools is installed in the "
"traditional way (e.g. not an editable install), and/or make sure "
"that setuptools is always imported before distutils."
)


def clear_distutils():
if 'distutils' not in sys.modules:
return
import warnings

warnings.warn("Setuptools is replacing distutils.")
mods = [
name
for name in sys.modules
if name == "distutils" or name.startswith("distutils.")
]
for name in mods:
del sys.modules[name]


def enabled():
"""
Allow selection of distutils by environment variable.
"""
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
return which == 'local'


def ensure_local_distutils():
import importlib

clear_distutils()

# With the DistutilsMetaFinder in place,
# perform an import to cause distutils to be
# loaded from setuptools._distutils. Ref #2906.
with shim():
importlib.import_module('distutils')

# check that submodules load as expected
core = importlib.import_module('distutils.core')
assert '_distutils' in core.__file__, core.__file__
assert 'setuptools._distutils.log' not in sys.modules


def do_override():
"""
Ensure that the local copy of distutils is preferred over stdlib.
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
for more motivation.
"""
if enabled():
warn_distutils_present()
ensure_local_distutils()


class _TrivialRe:
def __init__(self, *patterns):
self._patterns = patterns

def match(self, string):
return all(pat in string for pat in self._patterns)


class DistutilsMetaFinder:
def find_spec(self, fullname, path, target=None):
# optimization: only consider top level modules and those
# found in the CPython test suite.
if path is not None and not fullname.startswith('test.'):
return

method_name = 'spec_for_{fullname}'.format(**locals())
method = getattr(self, method_name, lambda: None)
return method()

def spec_for_distutils(self):
if self.is_cpython():
return

import importlib
import importlib.abc
import importlib.util

try:
mod = importlib.import_module('setuptools._distutils')
except Exception:
# There are a couple of cases where setuptools._distutils
# may not be present:
# - An older Setuptools without a local distutils is
# taking precedence. Ref #2957.
# - Path manipulation during sitecustomize removes
# setuptools from the path but only after the hook
# has been loaded. Ref #2980.
# In either case, fall back to stdlib behavior.
return

class DistutilsLoader(importlib.abc.Loader):
def create_module(self, spec):
mod.__name__ = 'distutils'
return mod

def exec_module(self, module):
pass

return importlib.util.spec_from_loader(
'distutils', DistutilsLoader(), origin=mod.__file__
)

@staticmethod
def is_cpython():
"""
Suppress supplying distutils for CPython (build and tests).
Ref #2965 and #3007.
"""
return os.path.isfile('pybuilddir.txt')

def spec_for_pip(self):
"""
Ensure stdlib distutils when running under pip.
See pypa/pip#8761 for rationale.
"""
if self.pip_imported_during_build():
return
clear_distutils()
self.spec_for_distutils = lambda: None

@classmethod
def pip_imported_during_build(cls):
"""
Detect if pip is being imported in a build script. Ref #2355.
"""
import traceback

return any(
cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
)

@staticmethod
def frame_file_is_setup(frame):
"""
Return True if the indicated frame suggests a setup.py file.
"""
# some frames may not have __file__ (#2940)
return frame.f_globals.get('__file__', '').endswith('setup.py')

def spec_for_sensitive_tests(self):
"""
Ensure stdlib distutils when running select tests under CPython.
python/cpython#91169
"""
clear_distutils()
self.spec_for_distutils = lambda: None

sensitive_tests = (
[
'test.test_distutils',
'test.test_peg_generator',
'test.test_importlib',
]
if sys.version_info < (3, 10)
else [
'test.test_distutils',
]
)


for name in DistutilsMetaFinder.sensitive_tests:
setattr(
DistutilsMetaFinder,
f'spec_for_{name}',
DistutilsMetaFinder.spec_for_sensitive_tests,
)


DISTUTILS_FINDER = DistutilsMetaFinder()


def add_shim():
DISTUTILS_FINDER in sys.meta_path or insert_shim()


class shim:
def __enter__(self):
insert_shim()

def __exit__(self, exc, value, tb):
remove_shim()


def insert_shim():
sys.meta_path.insert(0, DISTUTILS_FINDER)


def remove_shim():
try:
sys.meta_path.remove(DISTUTILS_FINDER)
except ValueError:
pass
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__import__('_distutils_hack').do_override()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'local') == 'local'; enabled and __import__('_distutils_hack').add_shim();
Loading

0 comments on commit 1a2534c

Please sign in to comment.