felixchiuman commited on
Commit
9884551
·
1 Parent(s): e8f784d

created for hugging face space

Browse files
.idea/MentalHealthApi.iml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.venv" />
6
+ </content>
7
+ <orderEntry type="jdk" jdkName="Python 3.12 (MentalHealthApi)" jdkType="Python SDK" />
8
+ <orderEntry type="sourceFolder" forTests="false" />
9
+ </component>
10
+ </module>
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/MentalHealthApi.iml" filepath="$PROJECT_DIR$/.idea/MentalHealthApi.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
.idea/workspace.xml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ChangeListManager">
4
+ <list default="true" id="28f98b15-03b6-46d3-96ff-cb09b54e30e9" name="Changes" comment="" />
5
+ <option name="SHOW_DIALOG" value="false" />
6
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
7
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
8
+ <option name="LAST_RESOLUTION" value="IGNORE" />
9
+ </component>
10
+ <component name="Git.Settings">
11
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
12
+ </component>
13
+ <component name="ProjectColorInfo"><![CDATA[{
14
+ "associatedIndex": 2
15
+ }]]></component>
16
+ <component name="ProjectId" id="2vUl6kvbUHpwQdLCky5l3NhaUrr" />
17
+ <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
18
+ <component name="ProjectViewState">
19
+ <option name="hideEmptyMiddlePackages" value="true" />
20
+ <option name="showLibraryContents" value="true" />
21
+ </component>
22
+ <component name="PropertiesComponent"><![CDATA[{
23
+ "keyToString": {
24
+ "RunOnceActivity.ShowReadmeOnStart": "true",
25
+ "git-widget-placeholder": "master"
26
+ }
27
+ }]]></component>
28
+ <component name="SharedIndexes">
29
+ <attachedChunks>
30
+ <set>
31
+ <option value="bundled-python-sdk-1b1018131e27-aa17d162503b-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-243.22562.180" />
32
+ </set>
33
+ </attachedChunks>
34
+ </component>
35
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
36
+ <component name="TaskManager">
37
+ <task active="true" id="Default" summary="Default task">
38
+ <changelist id="28f98b15-03b6-46d3-96ff-cb09b54e30e9" name="Changes" comment="" />
39
+ <created>1744207365425</created>
40
+ <option name="number" value="Default" />
41
+ <option name="presentableId" value="Default" />
42
+ <updated>1744207365425</updated>
43
+ </task>
44
+ <servers />
45
+ </component>
46
+ </project>
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import (
4
+ AutoTokenizer,
5
+ AutoModelForSeq2SeqLM,
6
+ pipeline,
7
+ AutoModelForSequenceClassification,
8
+ AutoModelForCausalLM
9
+ )
10
+
11
+ # Hugging Face login token (only needed for private models or DeepSeek)
12
+ import os
13
+ from huggingface_hub import login
14
+
15
+ hf_token = os.getenv("HF_TOKEN")
16
+ login(hf_token)
17
+
18
+ # Load PTSD summarization model
19
+ model_name = "machinelearningzuu/ptsd-summarization"
20
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
21
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
22
+ summarizer = pipeline("summarization", model=model, tokenizer=tokenizer)
23
+
24
+ # Sentiment analysis
25
+ sentiment_analyzer = pipeline("sentiment-analysis")
26
+
27
+ # Emotion classification
28
+ clf_model = AutoModelForSequenceClassification.from_pretrained("nateraw/bert-base-uncased-emotion")
29
+ clf_tokenizer = AutoTokenizer.from_pretrained("nateraw/bert-base-uncased-emotion")
30
+ labels = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
31
+
32
+ def classify_mental_state(text):
33
+ inputs = clf_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
34
+ with torch.no_grad():
35
+ outputs = clf_model(**inputs)
36
+ logits = outputs.logits
37
+ probs = torch.nn.functional.softmax(logits, dim=1)
38
+ top_idx = torch.argmax(probs).item()
39
+ label = labels[top_idx]
40
+ confidence = probs[0][top_idx].item()
41
+ return f"{label.capitalize()} ({confidence:.2f})"
42
+
43
+ # DeepSeek suggestion generator
44
+ deepseek_model_id = "deepseek-ai/deepseek-llm-7b-chat"
45
+ deepseek_tokenizer = AutoTokenizer.from_pretrained(deepseek_model_id)
46
+ deepseek_model = AutoModelForCausalLM.from_pretrained(
47
+ deepseek_model_id,
48
+ torch_dtype=torch.float16,
49
+ device_map="auto",
50
+ token=True
51
+ )
52
+ deepseek_tokenizer.pad_token = deepseek_tokenizer.eos_token
53
+
54
+ def generate_suggestion(summary_text):
55
+ prompt = (
56
+ f"Patient summary: {summary_text}\n"
57
+ f"Based on this, provide 3 specific coping suggestions for PTSD symptoms:\n"
58
+ f"1."
59
+ )
60
+ inputs = deepseek_tokenizer([prompt], return_tensors="pt", padding=True, truncation=True).to(deepseek_model.device)
61
+ outputs = deepseek_model.generate(
62
+ input_ids=inputs["input_ids"],
63
+ attention_mask=inputs["attention_mask"],
64
+ max_new_tokens=200,
65
+ do_sample=True,
66
+ temperature=0.7,
67
+ eos_token_id=deepseek_tokenizer.eos_token_id,
68
+ pad_token_id=deepseek_tokenizer.pad_token_id
69
+ )
70
+ generated = deepseek_tokenizer.decode(outputs[0], skip_special_tokens=True)
71
+ suggestion = generated.split("1.", 1)[-1].strip()
72
+ return "1. " + suggestion
73
+
74
+ # Main logic for Gradio
75
+ def analyze_input(text):
76
+ try:
77
+ summary = summarizer(text, max_length=100, min_length=10, do_sample=False)[0]['summary_text']
78
+ sentiment = sentiment_analyzer(text)[0]
79
+ sentiment_result = f"{sentiment['label']} ({sentiment['score']:.2f})"
80
+ classification_result = classify_mental_state(text)
81
+ suggestion = generate_suggestion(summary)
82
+ return summary, sentiment_result, classification_result, suggestion
83
+ except Exception as e:
84
+ return "Error: " + str(e), "Error", "Error", "Error"
85
+
86
+ # Gradio UI
87
+ demo = gr.Interface(
88
+ fn=analyze_input,
89
+ inputs=[gr.Textbox(lines=10, placeholder="Enter patient report...", label="Patient Report")],
90
+ outputs=[
91
+ gr.Textbox(label="Summary"),
92
+ gr.Textbox(label="Sentiment Analysis"),
93
+ gr.Textbox(label="Mental Health Indicator"),
94
+ gr.Textbox(label="Suggested Advice")
95
+ ],
96
+ title="Mental Health Assistant",
97
+ description="Summarizes PTSD-related text, detects emotional tone, classifies mental state, and generates non-clinical coping suggestions."
98
+ )
99
+
100
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ transformers
3
+ torch
4
+ huggingface_hub
5
+ accelerate