cooperchris17 commited on
Commit
d1865a8
·
verified ·
1 Parent(s): 5cba0a3

Upload 2 files

Browse files
Files changed (2) hide show
  1. ConstructionComplexityCalculator.py +108 -112
  2. Dockerfile +18 -21
ConstructionComplexityCalculator.py CHANGED
@@ -1,112 +1,108 @@
1
- from flask import Flask, request, render_template, send_from_directory
2
- import stanza
3
- import pandas as pd
4
- import os
5
- import platform
6
- import scipy.stats as stats
7
-
8
- # Set a directory within the /tmp directory for Stanza resources
9
- stanza_dir = os.path.join('/tmp', 'stanza_resources')
10
- os.makedirs(stanza_dir, exist_ok=True)
11
-
12
- # Initialize the Stanza pipeline with the custom directory
13
- nlp = stanza.Pipeline("en", dir=stanza_dir)
14
-
15
- app = Flask(__name__)
16
-
17
- # Function to calculate diversity (Shannon's entropy) of a sentence
18
- def sentence_diversity_calc(tags):
19
- pairs = [(tags[i], tags[i+1]) for i in range(len(tags) - 1)]
20
- pair_counts = {pair: pairs.count(pair) for pair in pairs}
21
- total_pairs = sum(pair_counts.values())
22
- probabilities = [count / total_pairs for count in pair_counts.values()]
23
- return stats.entropy(probabilities, base=2)
24
-
25
- # Function to calculate the productivity of each sentence
26
- def sentence_productivity_calc(words, tags):
27
- word_tag_pairs = list(zip(words, tags))
28
- pair_counts = {pair: word_tag_pairs.count(pair) for pair in word_tag_pairs}
29
- total_pairs = sum(pair_counts.values())
30
- probabilities = [count / total_pairs for count in pair_counts.values()]
31
- H_WT = stats.entropy(probabilities, base=2)
32
-
33
- tag_counts = {tag: tags.count(tag) for tag in tags}
34
- total_tags = sum(tag_counts.values())
35
- tag_probabilities = [count / total_tags for count in tag_counts.values()]
36
- H_T = stats.entropy(tag_probabilities, base=2)
37
-
38
- H_WT_given_T = H_WT - H_T
39
- return H_WT_given_T + 1
40
-
41
- # Function to calculate the document complexity
42
- def document_complexity_calc(sentences, doc):
43
- N = len(sentences)
44
- total_complexity = total_diversity = total_productivity = 0
45
-
46
- for sentence in sentences:
47
- sen_words = [word.text.lower() for word in sentence.words if word.upos != "PUNCT"]
48
- sen_pos = [word.xpos for word in sentence.words if word.upos != "PUNCT"]
49
-
50
- diversity = sentence_diversity_calc(sen_pos)
51
- productivity = sentence_productivity_calc(sen_words, sen_pos)
52
-
53
- total_complexity += diversity * productivity
54
- total_diversity += diversity
55
- total_productivity += productivity
56
-
57
- return total_complexity / N, total_diversity / N, total_productivity / N
58
-
59
- @app.route('/')
60
- def index():
61
- return render_template('index.html')
62
-
63
- @app.route('/process', methods=['POST'])
64
- def process():
65
- text = request.form.get('text', '')
66
- files = request.files.getlist('files')
67
- results = []
68
-
69
- if text:
70
- doc = nlp(text)
71
- complexity, avg_diversity, avg_productivity = document_complexity_calc(doc.sentences, doc)
72
- return f"""
73
- Complexity score: {complexity}<br>
74
- Diversity: {avg_diversity}<br>
75
- Productivity: {avg_productivity}
76
- """
77
-
78
- elif files:
79
- for uploaded_file in files:
80
- if not uploaded_file.filename.endswith('.txt'):
81
- return "Only .txt files are allowed."
82
-
83
- content = uploaded_file.read().decode('utf-8')
84
- doc = nlp(content)
85
- complexity, avg_diversity, avg_productivity = document_complexity_calc(doc.sentences, doc)
86
- results.append({'filename': uploaded_file.filename,
87
- 'complexity': complexity,
88
- 'diversity': avg_diversity,
89
- 'productivity': avg_productivity})
90
-
91
- df = pd.DataFrame(results)
92
-
93
- # Save the CSV file to a known directory
94
- downloads_folder = "/app/Downloads"
95
- os.makedirs(downloads_folder, exist_ok=True)
96
- csv_filename = os.path.join(downloads_folder, 'complexity_scores.csv')
97
- df.to_csv(csv_filename, index=False)
98
-
99
- # Provide a link to download the file
100
- return f"""
101
- Finished processing. <a href="/download/complexity_scores.csv">Download the CSV file</a>.
102
- """
103
-
104
- return "No input provided"
105
-
106
- @app.route('/download/<filename>')
107
- def download_file(filename):
108
- downloads_folder = "/app/Downloads"
109
- return send_from_directory(directory=downloads_folder, path=filename, as_attachment=True)
110
-
111
- if __name__ == "__main__":
112
- app.run(host="0.0.0.0", port=5000, debug=False)
 
1
+ from flask import Flask, request, render_template, send_from_directory
2
+ import stanza
3
+ import pandas as pd
4
+ import os
5
+ import platform
6
+ import scipy.stats as stats
7
+
8
+ app = Flask(__name__)
9
+
10
+ # Initialize the Stanza pipeline
11
+ nlp = stanza.Pipeline("en", dir="/app/stanza_resources") # Adjust path if needed
12
+
13
+ # Function to calculate diversity (Shannon's entropy) of a sentence
14
+ def sentence_diversity_calc(tags):
15
+ pairs = [(tags[i], tags[i+1]) for i in range(len(tags) - 1)]
16
+ pair_counts = {pair: pairs.count(pair) for pair in pairs}
17
+ total_pairs = sum(pair_counts.values())
18
+ probabilities = [count / total_pairs for count in pair_counts.values()]
19
+ return stats.entropy(probabilities, base=2)
20
+
21
+ # Function to calculate the productivity of each sentence
22
+ def sentence_productivity_calc(words, tags):
23
+ word_tag_pairs = list(zip(words, tags))
24
+ pair_counts = {pair: word_tag_pairs.count(pair) for pair in word_tag_pairs}
25
+ total_pairs = sum(pair_counts.values())
26
+ probabilities = [count / total_pairs for count in pair_counts.values()]
27
+ H_WT = stats.entropy(probabilities, base=2)
28
+
29
+ tag_counts = {tag: tags.count(tag) for tag in tags}
30
+ total_tags = sum(tag_counts.values())
31
+ tag_probabilities = [count / total_tags for count in tag_counts.values()]
32
+ H_T = stats.entropy(tag_probabilities, base=2)
33
+
34
+ H_WT_given_T = H_WT - H_T
35
+ return H_WT_given_T + 1
36
+
37
+ # Function to calculate the document complexity
38
+ def document_complexity_calc(sentences, doc):
39
+ N = len(sentences)
40
+ total_complexity = total_diversity = total_productivity = 0
41
+
42
+ for sentence in sentences:
43
+ sen_words = [word.text.lower() for word in sentence.words if word.upos != "PUNCT"]
44
+ sen_pos = [word.xpos for word in sentence.words if word.upos != "PUNCT"]
45
+
46
+ diversity = sentence_diversity_calc(sen_pos)
47
+ productivity = sentence_productivity_calc(sen_words, sen_pos)
48
+
49
+ total_complexity += diversity * productivity
50
+ total_diversity += diversity
51
+ total_productivity += productivity
52
+
53
+ return total_complexity / N, total_diversity / N, total_productivity / N
54
+
55
+ @app.route('/')
56
+ def index():
57
+ return render_template('index.html')
58
+
59
+ @app.route('/process', methods=['POST'])
60
+ def process():
61
+ text = request.form.get('text', '')
62
+ files = request.files.getlist('files')
63
+ results = []
64
+
65
+ if text:
66
+ doc = nlp(text)
67
+ complexity, avg_diversity, avg_productivity = document_complexity_calc(doc.sentences, doc)
68
+ return f"""
69
+ Complexity score: {complexity}<br>
70
+ Diversity: {avg_diversity}<br>
71
+ Productivity: {avg_productivity}
72
+ """
73
+
74
+ elif files:
75
+ for uploaded_file in files:
76
+ if not uploaded_file.filename.endswith('.txt'):
77
+ return "Only .txt files are allowed."
78
+
79
+ content = uploaded_file.read().decode('utf-8')
80
+ doc = nlp(content)
81
+ complexity, avg_diversity, avg_productivity = document_complexity_calc(doc.sentences, doc)
82
+ results.append({'filename': uploaded_file.filename,
83
+ 'complexity': complexity,
84
+ 'diversity': avg_diversity,
85
+ 'productivity': avg_productivity})
86
+
87
+ df = pd.DataFrame(results)
88
+
89
+ # Save the CSV file to a known directory
90
+ downloads_folder = "/app/Downloads"
91
+ os.makedirs(downloads_folder, exist_ok=True)
92
+ csv_filename = os.path.join(downloads_folder, 'complexity_scores.csv')
93
+ df.to_csv(csv_filename, index=False)
94
+
95
+ # Provide a link to download the file
96
+ return f"""
97
+ Finished processing. <a href="/download/complexity_scores.csv">Download the CSV file</a>.
98
+ """
99
+
100
+ return "No input provided"
101
+
102
+ @app.route('/download/<filename>')
103
+ def download_file(filename):
104
+ downloads_folder = "/app/Downloads"
105
+ return send_from_directory(directory=downloads_folder, path=filename, as_attachment=True)
106
+
107
+ if __name__ == "__main__":
108
+ app.run(host="0.0.0.0", port=5000, debug=False)
 
 
 
 
Dockerfile CHANGED
@@ -1,21 +1,18 @@
1
- # Use the official Python image from the Docker Hub
2
- FROM python:3.12-slim
3
-
4
- # Set the working directory in the container
5
- WORKDIR /app
6
-
7
- # Copy the requirements file into the container
8
- COPY requirements.txt .
9
-
10
- # Install the dependencies
11
- RUN pip install --upgrade pip && \
12
- pip install --no-cache-dir -r requirements.txt
13
-
14
- # Copy the rest of the application code into the container
15
- COPY . .
16
-
17
- # Expose the port the app runs on
18
- EXPOSE 5000
19
-
20
- # Define the command to run the application using gunicorn
21
- CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "ConstructionComplexityCalculator:app"]
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Copy default.zip
6
+ COPY default.zip /app/stanza_resources
7
+
8
+ # Install dependencies
9
+ COPY requirements.txt .
10
+ RUN pip install --upgrade pip && \
11
+ pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Copy your application code
14
+ COPY . .
15
+
16
+ EXPOSE 5000
17
+
18
+ CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "ConstructionComplexityCalculator:app"]