DeMaking commited on
Commit
75d2f8c
·
verified ·
1 Parent(s): 658db8a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -0
app.py CHANGED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # new app
2
+ import logging
3
+ import os
4
+ from fastapi import FastAPI, Request
5
+ from contextlib import asynccontextmanager
6
+ from transformers import pipeline
7
+ import langid
8
+ from huggingface_hub import login
9
+ import socket
10
+ import time
11
+
12
+ # Global variables
13
+ HF_HUB_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
14
+
15
+ def current_time_gmt():
16
+ return time.gmtime().tm_hour+2,':',time.gmtime().tm_min,':',time.gmtime().tm_sec
17
+
18
+ # Verify Hugging Face token
19
+ if not HF_HUB_TOKEN:
20
+ raise ValueError("Missing Hugging Face API token. Please set HUGGINGFACEHUB_API_TOKEN in environment variables.")
21
+ login(token=HF_HUB_TOKEN)
22
+
23
+
24
+ # Load Hebrew and English text generation models
25
+ lang_generator = pipeline("text-generation", model="gpt2")
26
+
27
+
28
+ # Function to detect language
29
+ def detect_language(user_input):
30
+ try:
31
+ lang, _ = langid.classify(user_input) # langid.classify returns a tuple (language, confidence)
32
+ print(f"Detected language: {lang}, ", f"current time: {current_time_gmt()}")
33
+ return "hebrew" if lang == "he" else "english" if lang == "en" else "unsupported"
34
+ except Exception as e:
35
+ print(f"Language detection error: {e}")
36
+ return "unsupported"
37
+
38
+
39
+ def generate_response(text):
40
+ language = detect_language(text)
41
+ print(f"Detected language: {language}, ", f"current time: {current_time_gmt()}")
42
+
43
+ if language == "hebrew" or language == "english":
44
+ # hebrew_generator = pipeline("text-generation", model="onlplab/alephbert-base")
45
+ output = lang_generator(text, max_length=100, truncation=True)
46
+ print(f"Model output: {output}, ", f"current time: {current_time_gmt()}") # Debugging
47
+ return output[0]["generated_text"]
48
+
49
+ # elif language == "english":
50
+ # #english_generator = pipeline("text-generation", model="mistralai/Mistral-Nemo-Instruct-2407", max_new_tokens=128)
51
+ # # english_generator = pipeline("text-generation", model="distilgpt2")
52
+ # output = english_generator(text, max_length=100, truncation=True)
53
+ # print(f"English model output: {output}, ", f"current time: {current_time_gmt()}") # Debugging
54
+ # return output[0]["generated_text"]
55
+
56
+ return "Sorry, I only support Hebrew and English."
57
+
58
+
59
+ # FastAPI lifespan event
60
+ @asynccontextmanager
61
+ async def lifespan(app: FastAPI):
62
+ print("Starting application...")
63
+ yield # Wait until app closes
64
+ print("Shutting down application...")
65
+
66
+
67
+ # Create FastAPI app
68
+ app = FastAPI(lifespan=lifespan)
69
+
70
+
71
+ @app.get("/")
72
+ async def root():
73
+ return {"message": "Decision Helper API is running!"}
74
+
75
+
76
+ @app.post("/generate_response")
77
+ async def generate_text(request: Request):
78
+ try:
79
+ data = await request.json()
80
+ if not data or "text" not in data:
81
+ logging.error("Invalid request received")
82
+ return {"error": "Invalid request. Please send JSON with a 'text' field."}
83
+
84
+ text = data["text"].strip()
85
+ if not text:
86
+ return {"error": "No text provided"}
87
+
88
+ print(f"Received text: {text}") # Debugging
89
+
90
+ response = generate_response(text)
91
+ print(f"Generated response: {response}") # Debugging
92
+ return {"response": response}
93
+
94
+ except Exception as e:
95
+ logging.error(f"Error processing request: {e}")
96
+ return {"error": "An unexpected error occurred."}
97
+
98
+
99
+ # Run the server
100
+ if __name__ == "__main__":
101
+ import uvicorn
102
+ uvicorn.run(app, host="0.0.0.0", port=7860)
103
+