luck210 commited on
Commit
d1a9496
·
verified ·
1 Parent(s): a0e137a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -78
app.py CHANGED
@@ -1,93 +1,184 @@
1
- from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import HTMLResponse
3
- from transformers import pipeline
4
 
5
- # Création de l'application FastAPI
6
- app = FastAPI(title="Traduction Anglais → Français")
7
 
8
- # Chargement du modèle de traduction
9
- translator = pipeline("translation_en_to_fr", model="Helsinki-NLP/opus-mt-en-fr")
 
 
10
 
11
- @app.get("/", response_class=HTMLResponse)
12
- def serve_html():
13
- """ Sert l'interface utilisateur en HTML """
14
- return """
15
- <!DOCTYPE html>
16
- <html lang="fr">
17
- <head>
18
- <meta charset="UTF-8">
19
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
20
- <title>Traduction Anglais → Français</title>
21
- <style>
22
- body { font-family: Arial, sans-serif; text-align: center; margin: 50px; background-color: #f4f4f4; }
23
- h2 { color: #333; }
24
- textarea { width: 80%; height: 100px; margin: 10px; padding: 10px; font-size: 16px; }
25
- button { padding: 10px 20px; font-size: 16px; background-color: #007BFF; color: white; border: none; cursor: pointer; }
26
- button:hover { background-color: #0056b3; }
27
- #output { margin-top: 20px; font-size: 18px; font-weight: bold; color: #28a745; }
28
- .loader { display: none; margin: 10px auto; border: 5px solid #f3f3f3; border-top: 5px solid #007BFF; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
29
- @keyframes spin { 100% { transform: rotate(360deg); } }
30
- </style>
31
- </head>
32
- <body>
33
- <h2>Traduction Anglais → Français</h2>
34
- <textarea id="textInput" placeholder="Entrez votre texte en anglais..."></textarea><br>
35
- <button onclick="translateText()">Traduire</button>
36
- <div class="loader" id="loader"></div>
37
- <p id="output"></p>
38
 
39
- <script>
40
- async function translateText() {
41
- let text = document.getElementById("textInput").value;
42
- let output = document.getElementById("output");
43
- let loader = document.getElementById("loader");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- if (!text.trim()) {
46
- output.innerText = "Veuillez entrer du texte !";
47
- output.style.color = "red";
48
- return;
49
- }
 
 
50
 
51
- loader.style.display = "block";
52
- output.innerText = "";
 
53
 
54
- try {
55
- let response = await fetch("/translate/", {
56
- method: "POST",
57
- headers: { "Content-Type": "application/json" },
58
- body: JSON.stringify({ text: text })
59
- });
60
 
61
- let data = await response.json();
62
- if (response.ok) {
63
- output.innerText = "Traduction : " + data.translated;
64
- output.style.color = "#28a745";
65
- } else {
66
- output.innerText = "Erreur : " + data.detail;
67
- output.style.color = "red";
68
- }
69
- } catch (error) {
70
- output.innerText = "Erreur de connexion.";
71
- output.style.color = "red";
72
- } finally {
73
- loader.style.display = "none";
74
- }
75
  }
76
- </script>
77
- </body>
78
- </html>
79
- """
 
80
 
81
- @app.post("/translate/")
82
- def translate(text: str):
83
- """ Traduit un texte de l'anglais vers le français """
84
- if not text:
85
- raise HTTPException(status_code=400, detail="Le texte est vide.")
86
 
 
 
 
 
 
87
  try:
88
- translated_text = translator(text)[0]['translation_text']
89
- return {"original": text, "translated": translated_text}
90
  except Exception as e:
91
- raise HTTPException(status_code=500, detail=f"Erreur de traduction : {e}")
92
-
93
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import HTMLResponse
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
 
5
+ app = FastAPI(title="Chatbot")
 
6
 
7
+ # Load the chatbot model (DialoGPT-medium) at startup
8
+ model_name = "microsoft/DialoGPT-medium"
9
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
10
+ model = AutoModelForCausalLM.from_pretrained(model_name)
11
 
12
+ # Function to generate chatbot response
13
+ def get_chatbot_response(user_input: str, max_length=100):
14
+ if not user_input:
15
+ return "Please say something!"
16
+
17
+ # Encode the input and generate a response
18
+ input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors="pt")
19
+ chat_history_ids = model.generate(
20
+ input_ids,
21
+ max_length=max_length,
22
+ pad_token_id=tokenizer.eos_token_id,
23
+ no_repeat_ngram_size=3,
24
+ do_sample=True,
25
+ top_k=50,
26
+ top_p=0.95,
27
+ temperature=0.8
28
+ )
29
+ # Decode the response, skipping the input part
30
+ response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
31
+ return response.strip()
 
 
 
 
 
 
 
32
 
33
+ # HTML, CSS, and JS embedded
34
+ HTML_CONTENT = """
35
+ <!DOCTYPE html>
36
+ <html lang="en">
37
+ <head>
38
+ <meta charset="UTF-8">
39
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
40
+ <title>Chatbot</title>
41
+ <style>
42
+ body {
43
+ font-family: Arial, sans-serif;
44
+ background-color: #f0f2f5;
45
+ margin: 0;
46
+ padding: 20px;
47
+ display: flex;
48
+ justify-content: center;
49
+ align-items: center;
50
+ min-height: 100vh;
51
+ }
52
+ .container {
53
+ max-width: 800px;
54
+ width: 100%;
55
+ padding: 2rem;
56
+ background: white;
57
+ border-radius: 10px;
58
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
59
+ }
60
+ h1 {
61
+ color: #2c3e50;
62
+ text-align: center;
63
+ margin-bottom: 2rem;
64
+ }
65
+ .chat-area {
66
+ max-height: 400px;
67
+ overflow-y: auto;
68
+ margin-bottom: 1.5rem;
69
+ padding: 1rem;
70
+ background: #f9f9f9;
71
+ border: 2px solid #eee;
72
+ border-radius: 5px;
73
+ }
74
+ .message {
75
+ margin: 0.5rem 0;
76
+ padding: 0.8rem;
77
+ border-radius: 5px;
78
+ }
79
+ .user-message {
80
+ background-color: #3498db;
81
+ color: white;
82
+ margin-left: 20%;
83
+ text-align: right;
84
+ }
85
+ .bot-message {
86
+ background-color: #ecf0f1;
87
+ color: #2c3e50;
88
+ margin-right: 20%;
89
+ }
90
+ .input-section {
91
+ display: flex;
92
+ gap: 1rem;
93
+ }
94
+ input[type="text"] {
95
+ flex: 1;
96
+ padding: 0.8rem;
97
+ border: 2px solid #ddd;
98
+ border-radius: 5px;
99
+ font-size: 1rem;
100
+ }
101
+ button {
102
+ padding: 0.8rem 1.5rem;
103
+ background-color: #3498db;
104
+ color: white;
105
+ border: none;
106
+ border-radius: 5px;
107
+ cursor: pointer;
108
+ font-size: 1rem;
109
+ transition: background-color 0.3s;
110
+ }
111
+ button:hover {
112
+ background-color: #2980b9;
113
+ }
114
+ </style>
115
+ </head>
116
+ <body>
117
+ <div class="container">
118
+ <h1>Chatbot</h1>
119
+ <div class="chat-area" id="chatArea"></div>
120
+ <div class="input-section">
121
+ <input type="text" id="userInput" placeholder="Type your message..." onkeypress="if(event.key === 'Enter') sendMessage();">
122
+ <button onclick="sendMessage()">Send</button>
123
+ </div>
124
+ </div>
125
+ <script>
126
+ const chatArea = document.getElementById("chatArea");
127
+ const userInput = document.getElementById("userInput");
128
 
129
+ function addMessage(text, isUser = false) {
130
+ const messageDiv = document.createElement("div");
131
+ messageDiv.className = "message " + (isUser ? "user-message" : "bot-message");
132
+ messageDiv.textContent = text;
133
+ chatArea.appendChild(messageDiv);
134
+ chatArea.scrollTop = chatArea.scrollHeight;
135
+ }
136
 
137
+ async function sendMessage() {
138
+ const text = userInput.value.trim();
139
+ if (!text) return;
140
 
141
+ addMessage(text, true);
142
+ userInput.value = "";
143
+ addMessage("Thinking...");
 
 
 
144
 
145
+ try {
146
+ const response = await fetch("/chat", {
147
+ method: "POST",
148
+ headers: { "Content-Type": "application/json" },
149
+ body: JSON.stringify({ message: text })
150
+ });
151
+ const data = await response.json();
152
+ if (!response.ok) throw new Error(data.detail || "Chat error");
153
+
154
+ chatArea.lastChild.remove();
155
+ addMessage(data.response);
156
+ } catch (error) {
157
+ chatArea.lastChild.remove();
158
+ addMessage(`Error: ${error.message}`);
159
  }
160
+ }
161
+ </script>
162
+ </body>
163
+ </html>
164
+ """
165
 
166
+ @app.get("/", response_class=HTMLResponse)
167
+ async def read_root():
168
+ return HTML_CONTENT
 
 
169
 
170
+ @app.post("/chat")
171
+ async def chat_endpoint(data: dict):
172
+ message = data.get("message", "")
173
+ if not message:
174
+ raise HTTPException(status_code=400, detail="No message provided")
175
  try:
176
+ response = get_chatbot_response(message)
177
+ return {"response": response}
178
  except Exception as e:
179
+ raise HTTPException(status_code=500, detail=f"Chat error: {str(e)}")
 
180
 
181
+ if __name__ == "__main__":
182
+ import uvicorn
183
+ # Modified to use port 7860 for Hugging Face Spaces
184
+ uvicorn.run(app, host="0.0.0.0", port=7860)