sanketshinde3001 commited on
Commit
6cad8c2
·
verified ·
1 Parent(s): a0a4aa0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -21
app.py CHANGED
@@ -1,7 +1,6 @@
1
- from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
- from transformers import pipeline
5
  import difflib
6
  import spacy
7
  import re
@@ -9,13 +8,8 @@ from nltk.sentiment import SentimentIntensityAnalyzer
9
  import nltk
10
  from collections import Counter
11
  import uvicorn
12
- import requests
13
- from dotenv import load_dotenv
14
  import os
15
-
16
- load_dotenv()
17
-
18
- HF_API_TOKEN = os.getenv("HF_API_TOKEN")
19
 
20
  # Download NLTK resources
21
  try:
@@ -34,23 +28,39 @@ app.add_middleware(
34
  allow_credentials=True,
35
  allow_methods=["*"], # Allows all methods
36
  allow_headers=["*"], # Allows all headers
37
- )
38
 
39
- humanize_pipe = None # Default to None before trying to load
 
 
 
 
 
40
 
41
- try:
42
- # humanize_pipe = pipeline("text2text-generation", model="danibor/flan-t5-base-humanizer")
43
- print("Humanization model loaded successfully!")
 
44
 
 
 
 
 
 
 
 
 
 
 
45
  # Load spaCy model
46
  nlp = spacy.load("en_core_web_sm")
47
 
48
  # Initialize sentiment analyzer
49
  sentiment_analyzer = SentimentIntensityAnalyzer()
50
 
51
- print("All NLP models loaded successfully!")
52
  except Exception as e:
53
- print(f"Error loading humanization model: {e}")
54
  # Create fallback functions if models fail to load
55
  def mock_function(text):
56
  return "Model could not be loaded. This is a fallback response."
@@ -77,15 +87,12 @@ class AnalyzeResponse(BaseModel):
77
  complexity: dict
78
 
79
  @app.post("/humanize", response_model=HumanizeResponse)
80
- async def humanize_text(request: TextRequest):
81
  input_text = request.text
82
 
83
  try:
84
- API_URL = "https://api-inference.huggingface.co/models/danibor/flan-t5-base-humanizer"
85
- headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
86
-
87
- response = requests.post(API_URL, headers=headers, json={"inputs": text})
88
- humanized_text = response.json()[0]["generated_text"]
89
 
90
  # Get the differences
91
  diff = get_diff(input_text, humanized_text)
 
1
+ from fastapi import FastAPI, HTTPException, Depends
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
 
4
  import difflib
5
  import spacy
6
  import re
 
8
  import nltk
9
  from collections import Counter
10
  import uvicorn
 
 
11
  import os
12
+ import requests
 
 
 
13
 
14
  # Download NLTK resources
15
  try:
 
28
  allow_credentials=True,
29
  allow_methods=["*"], # Allows all methods
30
  allow_headers=["*"], # Allows all headers
31
+ )
32
 
33
+ # Function to get API token
34
+ def get_hf_api_token():
35
+ token = os.getenv("HF_API_TOKEN")
36
+ if not token:
37
+ raise HTTPException(status_code=500, detail="Hugging Face API token not configured")
38
+ return token
39
 
40
+ # Function to call Hugging Face Inference API
41
+ def get_humanized_text(text, token):
42
+ API_URL = "https://api-inference.huggingface.co/models/danibor/flan-t5-base-humanizer"
43
+ headers = {"Authorization": f"Bearer {token}"}
44
 
45
+ try:
46
+ response = requests.post(API_URL, headers=headers, json={"inputs": text})
47
+ response.raise_for_status() # Raise exception for HTTP errors
48
+ return response.json()[0]["generated_text"]
49
+ except Exception as e:
50
+ print(f"Error calling Hugging Face API: {e}")
51
+ return "Error processing text with Hugging Face API."
52
+
53
+ # Load NLP models
54
+ try:
55
  # Load spaCy model
56
  nlp = spacy.load("en_core_web_sm")
57
 
58
  # Initialize sentiment analyzer
59
  sentiment_analyzer = SentimentIntensityAnalyzer()
60
 
61
+ print("NLP models loaded successfully!")
62
  except Exception as e:
63
+ print(f"Error loading models: {e}")
64
  # Create fallback functions if models fail to load
65
  def mock_function(text):
66
  return "Model could not be loaded. This is a fallback response."
 
87
  complexity: dict
88
 
89
  @app.post("/humanize", response_model=HumanizeResponse)
90
+ async def humanize_text(request: TextRequest, hf_token: str = Depends(get_hf_api_token)):
91
  input_text = request.text
92
 
93
  try:
94
+ # Generate humanized text using Hugging Face API
95
+ humanized_text = get_humanized_text(input_text, hf_token)
 
 
 
96
 
97
  # Get the differences
98
  diff = get_diff(input_text, humanized_text)