IBM Watson Api Visual Recognition Error - java

I am trying to implement Watson API for visual recognition. I encounter the following error message:
Here is the code:
public class VisualRecognizer {
private VisualRecognition service;
public VisualRecognizer() {
this.service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
this.service.setApiKey("ourkey");
this.service.setEndPoint("https://gateway-a.watsonplatform.net/visual-recognition/api");
}
public String classifyImage(String filePath) throws FileNotFoundException {
InputStream imageStream = new FileInputStream(filePath);
ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
.imagesFile(imageStream)
.build();
ClassifiedImages result = service.classify(classifyOptions).execute();
Any suggestions on how to solve this would be greatly appreciated.

Please mention a file name.
ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
.imagesFile(imageStream).imagesFilename("xyz.jpg")
.build();
For me it worked

Related

How can I use custom font in Jeuclid (Java)?

this is the code where I am converting MathMl to png
public static void main(String[] args) throws IOException, FontFormatException {
Converter converter = Converter.getInstance();
String math="<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mfenced open=\"[\" close=\"]\"><mtable><mtr><mtd><mn>3</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr><mtd><mn>6</mn></mtd><mtd><mn>7</mn></mtd></mtr><mtr><mtd><mn>6</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced><mo>=</mo><msubsup><mo>∫</mo><mn>5</mn><mn>4</mn></msubsup></math>";
File inputFile = new File("D:\\mathml.xml");
File outputFile = new File("D:\\image.jpg");
//params to mention the size of image
MutableLayoutContext params = new LayoutContextImpl(
LayoutContextImpl.getDefaultLayoutContext());
params.setParameter(Parameter.MATHSIZE, 50f);
Document doc = StringToDocumentToString.convertStringToDocument(math);
// Parameter parameter= new Pa
converter.convert(doc, outputFile , "image/jpeg", params);
}
I want to use Tahoma.ttf when I make png from MathMl but I can not find any resource how to do that. Please can anyone help me?

Getting list of all Google Drive folders returns only one folder

I'm working on some improvement on our google drive integration.
Current state:
There is already implementation of saving files into Google Drive folders using hard-coded folderId. This works with no problems.
Now: I want to extend this logic and I need for this list of all folders.
So I followed this guide:
https://developers.google.com/drive/api/guides/search-files
And the problem is that I receive only **one** folder but in google drive there is 10.
Can anyone has any idea what I missed or overlooked? Why result doesn't contain nextPageToken? Spent whole day on it and this drives me crazy.
This is my method (i'm using service account for connection):
#Override
public List<File> getAllFolders() throws IOException {
Drive service = googleDriveProvider.getService();
List<File> files = new ArrayList<>();
String pageToken = null;
do {
FileList result = service.files().list()
.setQ("mimeType='application/vnd.google-apps.folder'")
.setSpaces("drive")
.setSupportsAllDrives(true)
.setIncludeItemsFromAllDrives(true)
.setFields("nextPageToken, files(id, name, parents)")
.setPageToken(pageToken)
.execute();
for (File file : result.getFiles()) {
System.out.printf("Found file: %s (%s)\n",
file.getName(), file.getId());
}
files.addAll(result.getFiles());
pageToken = result.getNextPageToken();
} while (pageToken != null);
return files;
}
And this is GoogleDriveProvider:
#Service
public class GoogleDriveProvider {
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final Set<String> SCOPES = DriveScopes.all();
private static final String GET_DRIVE_SERVICE_ERROR_MESSAGE = "Getting instance of Google drive has failed, error: [%s]";
#Value("${google.drive.service.account.auth.json}")
private String authJson;
#Value("${info.app.name}")
private String appName;
public Drive getService() throws GoogleDriveException {
try {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials credentials = GoogleCredentials.fromStream(
new ByteArrayInputStream(authJson.getBytes())).createScoped(SCOPES);
credentials.refreshIfExpired();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
return new Drive.Builder(httpTransport, JSON_FACTORY, requestInitializer)
.setApplicationName(appName)
.build();
} catch (IOException | GeneralSecurityException e) {
throw new GoogleDriveException(
format(GET_DRIVE_SERVICE_ERROR_MESSAGE, e.getMessage()), e);
}
}
}
Problem solved. Folders must be created by the service account or must be shared with service account first.

Why Java Azure Function App freezes when trying to access Azure datalake?

I am developing a Java Azure function that needs to download a file from Azure Datalake Gen2.
When the function tries to read the file, it freezes and no exception is thrown, and nothing is written to the console.
I am using the azure-storage-file-datalake SDK for Java dependency and this is my code:
import com.azure.storage.common.StorageSharedKeyCredential;
import com.azure.storage.file.datalake.DataLakeDirectoryClient;
import com.azure.storage.file.datalake.DataLakeFileClient;
import com.azure.storage.file.datalake.DataLakeFileSystemClient;
import com.azure.storage.file.datalake.DataLakeServiceClient;
import com.azure.storage.file.datalake.DataLakeServiceClientBuilder;
public DataLakeServiceClient GetDataLakeServiceClient(String accountName, String accountKey)
{
StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);
DataLakeServiceClientBuilder builder = new DataLakeServiceClientBuilder();
builder.endpoint("https://" + accountName + ".dfs.core.windows.net");
builder.credential(sharedKeyCredential);
return builder.buildClient();
}
public void DownloadFile(DataLakeFileSystemClient fileSystemClient, String fileName) throws Exception{
DataLakeDirectoryClient directoryClient = fileSystemClient.getDirectoryClient("DIR");
DataLakeDirectoryClient subdirClient= directoryClient.getSubdirectoryClient("SUBDIR");
DataLakeFileClient fileClient = subdirClient.getFileClient(fileName);
File file = new File("downloadedFile.txt");
OutputStream targetStream = new FileOutputStream(file);
fileClient.read(targetStream);
targetStream.close();
}
#FunctionName("func")
public HttpResponseMessage run(
#HttpTrigger(name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context
)
{
String fileName= request.getQueryParameters().get("file");
DataLakeServiceClient datalakeClient= GetDataLakeServiceClient("datalake", "<the shared key>");
DataLakeFileSystemClient datalakeFsClient= datalakeClient.getFileSystemClient("fs");
DownloadFile(datalakeFsClient, fileName);
}
The app freezes when it hits fileClient.read(targetStream);
I've tried with really small files, I've checked the credentials and the file paths, the access rights to datalake, I've switched to SAS token - the result is the same: no error at all, but the app freezes.
I am using these Maven dependencies:
<dependency>
<groupId>com.microsoft.azure.functions</groupId>
<artifactId>azure-functions-java-library</artifactId>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-file-datalake</artifactId>
<version>12.2.0</version>
</dependency>
so i was facing the same problem.Then i came across this.
https://github.com/Azure/azure-functions-java-library/issues/113
This worked for me on java 8,azure function v3.
Set FUNCTIONS_WORKER_JAVA_LOAD_APP_LIBS to True
in the function app Application settings.Then save and restart the function app.It will work.
Please check and do update if it worked for you as well.

How to get text paragraph dl4j neural networking

I'm working deeplearning4j and not understand how to get text paragraph of vector classified from the neural network.
I could only get classification rate.
This is my code:
public static void main(String[] args) throws Exception {
ClassPathResource resource = new ClassPathResource("paravec/recortes");
LabelAwareIterator iterator = new FileLabelAwareIterator.Builder()
.addSourceFolder(resource.getFile()).build();
TokenizerFactory t = new DefaultTokenizerFactory();
t.setTokenPreProcessor(new CommonPreprocessor());
ParagraphVectors paragraphVectors = new ParagraphVectors.Builder()
.learningRate(0.025).minLearningRate(0.001).batchSize(1000)
.epochs(10).iterate(iterator).trainWordVectors(true)
.tokenizerFactory(t).build();
paragraphVectors.fit();
ClassPathResource unlabeledResource = new ClassPathResource(
"paravec/caderno");
FileLabelAwareIterator unlabeledIterator = new FileLabelAwareIterator.Builder()
.addSourceFolder(unlabeledResource.getFile()).build();
MeansBuilder meansBuilder = new MeansBuilder(
(InMemoryLookupTable<VocabWord>) paragraphVectors
.getLookupTable(),
t);
LabelSeeker seeker = new LabelSeeker(iterator.getLabelsSource()
.getLabels(),
(InMemoryLookupTable<VocabWord>) paragraphVectors
.getLookupTable());
while (unlabeledIterator.hasNextDocument()) {
LabelledDocument document = unlabeledIterator.nextDocument();
//how to get text paragraph?
INDArray documentAsCentroid = meansBuilder
.documentAsVector(document);
}
}
Thanks!
Renan.

Java get metadata of public file on Google Drive

Hello I've downloaded and installed the latest version of Drive REST API for java and want to get the metadata of a public file from Google Drive by the fileID - I have the following code:
private static final String APPLICATION_NAME = "test";
private static final String FILE_ID = "theFileId";
public static void main(String[] args) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null).setApplicationName(APPLICATION_NAME).build();
printFile(service, FILE_ID);
}
private static void printFile(Drive service, String fileId) {
try {
File file = service.files().get(fileId).execute();
System.out.println("Title: " + file.getTitle());
} catch (IOException e) {
System.out.println("An error occured: " + e);
}
}
But I get the error message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
I've tried it on https://developers.google.com/drive/v2/reference/files/get which worked out just fine.
Do I have to authenticate with an API key when the file is public and how would I do that if so.
Thanks for your time.
Yes, you need to authenticate with an API key. See the documentation here: https://developers.google.com/drive/web/about-auth

Categories

Resources