ruthpark00 commited on
Commit
136a2c7
·
1 Parent(s): c28ab01

Add application file

Browse files
Files changed (5) hide show
  1. .DS_Store +0 -0
  2. Dockerfile +33 -0
  3. app.py +83 -0
  4. requirements.txt +3 -0
  5. test.http +9 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
Dockerfile ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # base image for Python
2
+ FROM python:3.9-slim
3
+
4
+ # set working directory in container 컨테이너 내 작업 디렉토리 설정
5
+ WORKDIR /app
6
+
7
+ # systemp package update & install dependancies
8
+ RUN apt-get update && apt-get install -y \
9
+ build-essential \
10
+ && apt-get clean \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ # copy requirements.txt
14
+ COPY requirements.txt .
15
+
16
+ # dependancy
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # copy app source code
20
+ COPY . .
21
+
22
+ # Expose the port the app runs on
23
+ EXPOSE 7860
24
+
25
+ # Define environment variable
26
+ ENV FLASK_APP=app.py
27
+
28
+ # Run the application
29
+ CMD ["flask", "run", "--host=0.0.0.0", "--port=7860"]
30
+ ## Hugging Face Spaces는 포트 7860을 사용
31
+ #ENV PORT 7860
32
+ ## set command
33
+ #CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+ import os
5
+
6
+
7
+ # Flask 앱 초기화
8
+ app = Flask(__name__)
9
+
10
+ # Load the BERTweet model and tokenizer
11
+ tokenizer = AutoTokenizer.from_pretrained("finiteautomata/bertweet-base-sentiment-analysis")
12
+ model = AutoModelForSequenceClassification.from_pretrained("finiteautomata/bertweet-base-sentiment-analysis")
13
+
14
+ LABELS = ['Negative', 'Neutral', 'Positive']
15
+
16
+ def analyze_sentiment(text):
17
+ # Converts text into tokens that the model can process
18
+ # return_tensors="pt": Returns PyTorch tensors
19
+ # truncation=True: Cuts text if it's too long
20
+ # padding=True: Adds padding to make sequences uniform length
21
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
22
+
23
+ # Predict with the model
24
+ # Passes tokenized input through the model
25
+ # Extracts logits (raw prediction scores) from model output
26
+ outputs = model(**inputs)
27
+ logits = outputs.logits
28
+
29
+ # Sentiment Classification:
30
+ # torch.argmax(): Finds index of highest score 가장 높은 값의 인덱스를 추출하여 감성 레이블을 선택
31
+ # Maps this index to a sentiment label using LABELS dictionary
32
+ # dim=1: Operates along rows, .item(): Converts tensor to Python scalar
33
+ predicted_class = torch.argmax(logits, dim=1).item()
34
+ sentiment = LABELS[predicted_class]
35
+
36
+ return sentiment
37
+
38
+ # API endpoint to analyze a text
39
+ @app.route('/analyze', methods=['POST'])
40
+ def analyze():
41
+ data = request.get_json()
42
+
43
+ if 'text' not in data:
44
+ return jsonify({'error': 'No text provided'}), 400
45
+
46
+ # call 감성 분석 function for 입력 텍스트
47
+ text = data['text']
48
+ sentiment = analyze_sentiment(text)
49
+
50
+ return jsonify({'text': text, 'sentiment': sentiment})
51
+
52
+ # API endpoint to analyze a list of texts
53
+ @app.route('/analyze_texts', methods=['POST'])
54
+ def analyze_texts():
55
+ data = request.get_json()
56
+
57
+ if 'texts' not in data:
58
+ return jsonify({'error': 'No texts provided'}), 400
59
+
60
+ # Perform analysis on each text in the list, process each one, and return a list of sentiment responses
61
+ texts = data['texts']
62
+ results = [{'text': text, 'sentiment': analyze_sentiment(text)} for text in texts]
63
+
64
+ # Count negative sentiments
65
+ negative_count = sum(1 for result in results if result['sentiment'] == 'Negative')
66
+
67
+ # Determine if it's a risk (more than half are negative)
68
+ risk = negative_count > (len(texts) / 2)
69
+
70
+ # Return the results as a JSON response
71
+ # return jsonify(results)
72
+ # Return the results and risk status as a JSON response
73
+ return jsonify({
74
+ 'results': results,
75
+ 'Negative Sentiment?': risk
76
+ })
77
+
78
+ # run
79
+
80
+ if __name__ == '__main__':
81
+ # 환경 변수 PORT를 우선 사용, 없으면 기본값 5000 사용
82
+ #port = int(os.getenv('PORT', 5001))
83
+ app.run(host='0.0.0.0', port=7860)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flask
2
+ torch
3
+ transformers
test.http ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ### Sentiment Analysis API test
2
+
3
+ POST http://0.0.0.0:5001/analyze_texts
4
+ Content-Type: application/json
5
+
6
+ {
7
+ "texts": ["I love using Flask for building APIs!", "not working", "Very happy"]
8
+ }
9
+