cloudwp commited on
Commit
ac5c525
1 Parent(s): 9c34cc1

Update backend.py

Browse files
Files changed (1) hide show
  1. backend.py +85 -37
backend.py CHANGED
@@ -1,73 +1,121 @@
1
  from flask import Flask, request, jsonify
2
  import requests
 
3
 
4
  app = Flask(__name__)
5
 
6
- class APIService:
7
- """Basisklasse für alle API-Dienste."""
8
- def __init__(self, api_key):
9
- self.api_key = api_key
 
 
 
 
 
 
 
 
 
 
10
 
11
- def fetch(self, *args, **kwargs):
12
- raise NotImplementedError("Diese Methode muss von Unterklassen implementiert werden.")
 
 
 
 
 
 
13
 
14
- class SynonymAPI(APIService):
15
- """API-Dienst für Synonyme."""
16
- def fetch(self, word):
17
- url = f"https://lingua-robot.p.rapidapi.com/language/v1/synonyms?word={word}"
18
  headers = {
19
- 'x-rapidapi-key': self.api_key,
20
  'x-rapidapi-host': "lingua-robot.p.rapidapi.com"
21
  }
22
- response = requests.get(url, headers=headers)
23
- return response.json()['entries'][0]['synonyms'] if response.status_code == 200 else []
 
 
 
 
 
 
 
 
24
 
25
- class GrammarAPI(APIService):
26
- """API-Dienst für Grammatik."""
27
- def fetch(self, text):
28
- response = requests.post(self.api_key, data={'text': text, 'language': 'en'})
29
  return response.json()['matches'] if response.status_code == 200 else []
30
 
 
31
  class APIManager:
32
- """Verwalten der APIs (Synonym und Grammatik)."""
33
  def __init__(self):
34
  self.synonym_api = None
35
  self.grammar_api = None
36
 
37
- def set_synonym_api(self, api):
38
- self.synonym_api = api
39
-
40
- def set_grammar_api(self, api):
41
- self.grammar_api = api
42
 
43
- def fetch_synonyms(self, word):
44
- return self.synonym_api.fetch(word) if self.synonym_api else "Keine Synonym-API konfiguriert."
45
 
46
- def fetch_grammar(self, text):
47
- return self.grammar_api.fetch(text) if self.grammar_api else "Keine Grammatik-API konfiguriert."
48
 
49
- # Instanziierung
50
  api_manager = APIManager()
51
 
52
- # API-Routen
53
  @app.route('/configure', methods=['POST'])
54
  def configure_apis():
55
  data = request.json
56
- synonym_api_key = data.get('synonym_api_key')
57
- grammar_api_key = data.get('grammar_api_key')
58
- api_manager.set_synonym_api(SynonymAPI(synonym_api_key))
59
- api_manager.set_grammar_api(GrammarAPI(grammar_api_key))
 
 
 
 
 
60
  return jsonify({"status": "APIs erfolgreich konfiguriert."})
61
 
 
62
  @app.route('/analyze-text', methods=['POST'])
63
  def analyze_text():
64
  data = request.json
65
  text = data.get('text')
 
 
 
66
  word = text.split()[0]
67
- synonyms = api_manager.fetch_synonyms(word)
68
- grammar = api_manager.fetch_grammar(text)
69
- return jsonify({"synonyms": synonyms, "grammar_suggestions": grammar})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # Start des Servers
72
  if __name__ == '__main__':
73
  app.run(debug=True)
 
1
  from flask import Flask, request, jsonify
2
  import requests
3
+ import json
4
 
5
  app = Flask(__name__)
6
 
7
+ # Laden der API-Keys aus einer Konfigurationsdatei
8
+ def load_api_keys():
9
+ with open("config.json", "r") as file:
10
+ return json.load(file)
11
+
12
+ # Speichern der API-Keys
13
+ def save_api_keys(api_keys):
14
+ with open("config.json", "w") as file:
15
+ json.dump(api_keys, file)
16
+
17
+ # API-Dienst für Synonyme (mit Fallback)
18
+ class SynonymAPI:
19
+ def __init__(self, api_keys):
20
+ self.api_keys = api_keys
21
 
22
+ def fetch(self, word, language='en'):
23
+ try:
24
+ response = self._fetch_from_primary_api(word, language)
25
+ if response.status_code == 200:
26
+ return response.json()['entries'][0]['synonyms']
27
+ except Exception:
28
+ # Fallback zur zweiten API, falls die erste nicht funktioniert
29
+ return self._fetch_from_secondary_api(word, language)
30
 
31
+ def _fetch_from_primary_api(self, word, language):
32
+ url = f"https://lingua-robot.p.rapidapi.com/language/v1/synonyms?word={word}&language={language}"
 
 
33
  headers = {
34
+ 'x-rapidapi-key': self.api_keys['primary'],
35
  'x-rapidapi-host': "lingua-robot.p.rapidapi.com"
36
  }
37
+ return requests.get(url, headers=headers)
38
+
39
+ def _fetch_from_secondary_api(self, word, language):
40
+ url = f"https://api.datamuse.com/words?rel_syn={word}&ml={language}"
41
+ return requests.get(url)
42
+
43
+ # API-Dienst für Grammatik
44
+ class GrammarAPI:
45
+ def __init__(self, api_key):
46
+ self.api_key = api_key
47
 
48
+ def fetch(self, text, language='en'):
49
+ response = requests.post(self.api_key, data={'text': text, 'language': language})
 
 
50
  return response.json()['matches'] if response.status_code == 200 else []
51
 
52
+ # API Manager zum Verwalten der Dienste
53
  class APIManager:
 
54
  def __init__(self):
55
  self.synonym_api = None
56
  self.grammar_api = None
57
 
58
+ def configure_apis(self, synonym_api_keys, grammar_api_key):
59
+ self.synonym_api = SynonymAPI(synonym_api_keys)
60
+ self.grammar_api = GrammarAPI(grammar_api_key)
 
 
61
 
62
+ def fetch_synonyms(self, word, language='en'):
63
+ return self.synonym_api.fetch(word, language) if self.synonym_api else "Keine Synonym-API konfiguriert."
64
 
65
+ def fetch_grammar(self, text, language='en'):
66
+ return self.grammar_api.fetch(text, language) if self.grammar_api else "Keine Grammatik-API konfiguriert."
67
 
68
+ # Instanziierung des API-Managers
69
  api_manager = APIManager()
70
 
71
+ # API-Konfiguration
72
  @app.route('/configure', methods=['POST'])
73
  def configure_apis():
74
  data = request.json
75
+ api_keys = {
76
+ 'synonym_api_keys': {
77
+ 'primary': data.get('synonym_primary_api_key'),
78
+ 'secondary': data.get('synonym_secondary_api_key')
79
+ },
80
+ 'grammar_api_key': data.get('grammar_api_key')
81
+ }
82
+ save_api_keys(api_keys)
83
+ api_manager.configure_apis(api_keys['synonym_api_keys'], api_keys['grammar_api_key'])
84
  return jsonify({"status": "APIs erfolgreich konfiguriert."})
85
 
86
+ # Textanalyse-API mit Zeichenanpassung
87
  @app.route('/analyze-text', methods=['POST'])
88
  def analyze_text():
89
  data = request.json
90
  text = data.get('text')
91
+ desired_length = data.get('desired_length', len(text))
92
+ language = data.get('language', 'en')
93
+
94
  word = text.split()[0]
95
+ synonyms = api_manager.fetch_synonyms(word, language)
96
+ grammar = api_manager.fetch_grammar(text, language)
97
+
98
+ # Zeichenanzahl berechnen und Anpassungsvorschläge geben
99
+ current_length = len(text)
100
+ length_difference = desired_length - current_length
101
+
102
+ response = {
103
+ "synonyms": synonyms,
104
+ "grammar_suggestions": grammar,
105
+ "current_length": current_length,
106
+ "desired_length": desired_length,
107
+ "length_difference": length_difference,
108
+ "adjustment_suggestions": []
109
+ }
110
+
111
+ # Vorschläge für Zeichenanzahl-Anpassung
112
+ if length_difference > 0:
113
+ response["adjustment_suggestions"].append(f"Fügen Sie {length_difference} Zeichen hinzu.")
114
+ elif length_difference < 0:
115
+ response["adjustment_suggestions"].append(f"Entfernen Sie {abs(length_difference)} Zeichen.")
116
+
117
+ return jsonify(response)
118
 
119
+ # Serverstart
120
  if __name__ == '__main__':
121
  app.run(debug=True)